How to apply a function to a tuple?

后端 未结 5 1925
迷失自我
迷失自我 2020-11-29 22:56

This should be an easy one. How do I apply a function to a tuple in Scala? Viz:

scala> def f (i : Int, j : Int) = i + j
f: (Int,Int)Int

scala> val p = (3,4)
p:          


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 23:37

    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 = 
    
    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.

提交回复
热议问题