Jacek Laskowski
Jacek Laskowski

Reputation: 74709

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

Upvotes: 16

Views: 7524

Answers (4)

Taras Z
Taras Z

Reputation: 21

Yes

def f(pair:(Int, Int)): Int =
    val (p1, p2) = pair
    p1

but why not just do?

def f(pair:(Int, Int)): Int = pair(0)

Upvotes: 0

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 }

Upvotes: 18

Jack Leow
Jack Leow

Reputation: 22487

It really depends on what problem you are trying to solve, but one idea is to use a tupled-function. In other words, define a function that takes two parameters, and .tupled it:

Welcome to Scala 3.2.1 (11.0.21, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
                                                                                
scala> def f_(p1: Int, p2: Int): Int = p1
def f_(p1: Int, p2: Int): Int
                                                                                
scala> val f = f_.tupled
val f: ((Int, Int)) => Int = scala.Function2$$Lambda$1337/0x0000000800737840@e6e5da4
                                                                                
scala> val pair = (1, 2)
val pair: (Int, Int) = (1,2)
                                                                                
scala> f(pair)
val res0: Int = 1

Upvotes: 0

Mark
Mark

Reputation: 86

def f(p: ((Int, Int), (Int, Int))) = p._1     > f: (p: ((Int, Int), (Int, Int)))(Int, Int)
f((1,2), (3,4))                               > res1: (Int, Int) = (1,2)

Upvotes: 0

Related Questions