John Threepwood John Threepwood - 1 year ago 76
Scala Question

How to pass a tuple argument the best way?

How to pass a tuple argument the best way ?


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

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

Now I would like to pass the output of
. 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
-tuple with
n > 2
. Also we have to store the result of foo in an extra value, because otherwise
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 Source

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:


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

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

See also

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download