Search code examples
scalaparameterstuplesiterable-unpacking

Will tuple unpacking be directly supported in parameter lists in Scala?


In Haskell you can write:

x :: (Int,Int) -> Int
x (p,s) = p

In Scala you would write:

def x(a: (Int, Int)) = a._1

or:

def x(a: (Int, Int)) = a match {
    case (p, s) => p
}

Why not have something like

def x(_: (p: Int, s: Int)) = p

or

def x(foo: (p @ Int, s @ Int)) = p

?


Solution

  • The feature you're looking for is called destructuring and, in it's general form, would go well beyond just tuple unpacking. I've often found myself wishing that Scala had it since it's such a natural extension of the pattern matching syntax:

    def first((f: Int, l: Int)) = f
    def displayName(Person(first, last)) = last + ", " + first
    

    Destructuring is (sort of) present in the form of variable/value definitions:

    val (f, l) = tuple
    val Person(first, last) = person
    

    Unfortunately, there are some type safety issues around such definitions that I think make it unlikely that you'll see destructuring in parameter lists any time soon.