Scala: tuple decomposition in function arguments

In python, I can do this:

def f((a, b)): return a + b d = (1, 2) f(d) 

Here, the one transferred to the tuple is decomposed, and it is transferred to f .

Right now in scala right now I am doing this:

 def f(ab:(Int, Int)) : Int = { val (a, b) = ab a + b } val d = (1, 2) f(d) 

Is there something I can do here to get the decomposition to happen while passing arguments? Just curious.

Thank.

+44
scala
Jul 23 2018-12-12T00:
source share
3 answers

You can create a function and map it to a template:

 scala> val f: ((Int, Int)) => Int = { case (a,b) => a+b } f: ((Int, Int)) => Int scala> f(1, 2) res0: Int = 3 

Or match the method input with the match keyword:

 scala> def f(ab: (Int, Int)): Int = ab match { case (a,b) => a+b } f: (ab: (Int, Int))Int scala> f(1, 2) res1: Int = 3 

Another way is to use a function with two arguments and its "tuple":

 scala> val f: (Int, Int) => Int = _+_ f: (Int, Int) => Int = <function2> scala> val g = f.tupled // or Function.tupled(f) g: ((Int, Int)) => Int = <function1> scala> g(1, 2) res10: Int = 3 // or with a method scala> def f(a: Int, b: Int): Int = a+b f: (a: Int, b: Int)Int scala> val g = (f _).tupled // or Function.tupled(f _) g: ((Int, Int)) => Int = <function1> scala> g(1, 2) res11: Int = 3 // or inlined scala> val f: ((Int,Int)) => Int = Function.tupled(_+_) f: ((Int, Int)) => Int = <function1> scala> f(1, 2) res12: Int = 3 
+69
Jul 23 '12 at 15:34
source share

What about:

  ab._1 + ab._2 

_1, _2 etc. access the various elements of a tuple.

+1
Jul 23 2018-12-23T00:
source share
 object RandomExperiments extends App{ def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n") takeTuple(1,3) takeTuple((1,3)) takeTuple(((1,3))) } 

prints:

 (1,3) 1 (1,3) 1 (1,3) 1 
+1
Apr 01 '17 at 16:22
source share



All Articles