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
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With