How to apply a function to a tuple?

后端 未结 5 1923
迷失自我
迷失自我 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:28

    In Scala 3, you can use TupledFunction:

    For a single use, you can do

    summon[TupledFunction[(Int, Int) => Int, ((Int, Int)) => Int]].tupled(f)((2, 3))
    

    To make it easier to use, you can use an extension (copied from Dotty's own documentation)

    extension [F, T <: Tuple, R](f: F)(using tf: TupledFunction[F, T => R])
      def tupled(t: T): R = tf.tupled(f)(t)
    

    And then you can do f.tupled((2, 3)) to get 5.

提交回复
热议问题