scalaclojure

Is destructuring input parameters available in Scala?


Is there a way to destructure input parameters of a function in Scala (akin to Clojure)?

So, instead of

scala> def f(p: (Int, Int)) = p._1
f: (p: (Int, Int))Int

I'd like to have this (it doesn't work):

scala> def f((p1, p2): (Int, Int)) = p1

Solution

  • I guess in scala you would use pattern matching to achieve the same, e.g. like this:

    val f: (Int, Int) => Int = { case (p1, p2) => p1 }
    

    Or, equivalently:

    def f(p: (Int, Int)) = p match { case(p1, p2) => p1 }
    

    If the types can be inferred, the (Int, Int) => Int can be dropped:

    List((1, 2), (3, 4)) map { case (p1, p2) => p1 }