How to apply a function to a tuple?
Solution 1:
In Scala 2.8 and newer:
scala> def f (i : Int, j : Int) = i + j
f: (i: Int,j: Int)Int
// Note the underscore after the f
scala> val ff = f _
ff: (Int, Int) => Int = <function2>
scala> val fft = ff.tupled
fft: ((Int, Int)) => Int = <function1>
In Scala 2.7:
scala> def f (i : Int, j : Int) = i + j
f: (Int,Int)Int
// Note the underscore after the f
scala> val ff = f _
ff: (Int, Int) => Int = <function>
scala> val fft = Function.tupled(ff)
fft: ((Int, Int)) => Int = <function>
Solution 2:
Following up on the other answer, one could write (tested with 2.11.4):
scala> def f (i: Int, j: Int) = i + j
f: (i: Int, j: Int)Int
scala> val ff = f _
ff: (Int, Int) => Int = <function2>
scala> val p = (3,4)
p: (Int, Int) = (3,4)
scala> ff.tupled(p)
res0: Int = 7
See def tupled: ((T1, T2)) ⇒ R:
Creates a tupled version of this function: instead of 2 arguments, it accepts a single scala.Tuple2 argument.
Solution 3:
Scala 2.13
def f (i : Int, j : Int) = i + j
import scala.util.chaining._
(3,4).pipe((f _).tupled) //res0: Int = 7