Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a shortcut to extract a tuple in a function paramenter in scala

Tags:

scala

val list = List((1,2), (3,4))

list.map(tuple => {
  val (a, b) = tuple
  do_something(a,b)
})

// the previous can be shortened as follows
list.map{ case(a, b) =>
  do_something(a,b)
}

// similarly, how can I shorten this (and avoid declaring the 'tuple' variable)?
def f(tuple: (Int, Int)) {
  val (a, b) = tuple
  do_something(a,b)
}

// here there two ways, but still not very short,
// and I could avoid declaring the 'tuple' variable
def f(tuple: (Int, Int)) {
  tuple match {
    case (a, b) => do_something(a,b)
  }
}

def f(tuple: (Int, Int)): Unit = tuple match {
  case (a, b) => do_something(a,b)
}
like image 645
David Portabella Avatar asked Jan 24 '26 22:01

David Portabella


1 Answers

Use tupled

scala> def doSomething = (a: Int, b: Int) => a + b
doSomething: (Int, Int) => Int

scala> doSomething.tupled((1, 2))
res0: Int = 3

scala> def f(tuple: (Int, Int)) = doSomething.tupled(tuple)
f: (tuple: (Int, Int))Int

scala> f((1,2))
res1: Int = 3

scala> f(1,2) // this is due to scala auto-tupling
res2: Int = 3

tupled is defined for every FunctionN with N >= 2, and returns a function expecting the parameters wrapped in a tuple.

like image 99
Gabriele Petronella Avatar answered Jan 27 '26 13:01

Gabriele Petronella