John Threepwood John Threepwood - 2 months ago 6
Scala Question

How to pass a tuple argument the best way?

How to pass a tuple argument the best way ?

Example:

def foo(...): (Int, Int) = ...

def bar(a: Int, b: Int) = ...


Now I would like to pass the output of
foo
to
bar
. This can be achieved with:

val fooResult = foo(...)
bar(fooResult._1, fooResult._2)


This approach looks a bit ugly, especially when we deal with a
n
-tuple with
n > 2
. Also we have to store the result of foo in an extra value, because otherwise
foo
has to be executed more than once using
bar(foo._1, foo._2)
.

Is there a better way to pass through the tuple as argument ?

Answer

There is a special tupled method available for every function:

val bar2 = (bar _).tupled  // or Function.tupled(bar _)

bar2 takes a tuple of (Int, Int) (same as bar arguments). Now you can say:

bar2(foo())

If your methods were actually functions (notice the val keyword) the syntax is much more pleasant:

val bar = (a: Int, b: Int) => //...
bar.tupled(foo())

See also

Comments