Decomposing tuples in function arguments

Viewed 44044

In python I can do this:

def f((a, b)):
    return a + b

d = (1, 2)
f(d)

Here the passed in tuple is being decomposed while its being passed to f.

Right now in scala I am doing this:

def f(ab: (Int, Int)): Int = {
    val (a, b) = ab
    a + b
}

val d = (1, 2)
f(d)

Is there something I can do here so that the decomposition happens while the arguments are passed in? Just curious.

3 Answers

Starting in Scala 3, with the improved tupled function feature:

// val tuple = (1, 2)
// def f(a: Int, b: Int): Int = a + b
f.tupled(tuple)
// 3

Play with it in Scastie

Related