Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is destructuring input parameters available in Scala?

Tags:

scala

clojure

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
like image 503
Jacek Laskowski Avatar asked May 01 '13 21:05

Jacek Laskowski


1 Answers

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 }
like image 136
ValarDohaeris Avatar answered Nov 20 '22 19:11

ValarDohaeris