sol4me
sol4me

Reputation: 15698

Scala correct syntax to use underscore("_") in function literal with tuple

I defined a function foo like

def foo(f : (Int, Int) => Int) = f(1,2) // just calling with some default vals

and can invoke it like

foo(_+_)  

But when i try to use the same way to invoke a function that takes IntPair(custom type) as param then i receive the error

error: wrong number of parameters; expected = 1

What is the correct syntax to invoke it

Sample Code

type IntPair = (Int, Int)  

def sum(f: (IntPair) => Int): (IntPair) => IntPair = {

def iter(pair: IntPair): IntPair = {
  val n = readLine()
  print(s"$n+")
  if (n != "q") {
    val (total, accum) = pair
    val p: IntPair = (f(n.toInt, total), accum + 1)
    iter(p)
  } else {
    pair
  }
}

   iter
}

i can invoke like

val f = sum((p : IntPair) => p._1 + p._2) // i want to use here  _ syntax
f((0,0))

but not like

val f = sum((_._1 + _._2)) //gives error

Upvotes: 3

Views: 1071

Answers (1)

kiritsuku
kiritsuku

Reputation: 53348

scala> def sum(p: ((Int, Int)) => Int) = p((2, 3))
sum: (p: ((Int, Int)) => Int)Int

scala> sum(Function.tupled(_+_))
res4: Int = 5

In Scala parameter lists and tuples are not unified, thus you can't simply pass a tuple to a function that expects multiple arguments.

sum(_._1 + _._2) means sum((x,y) => x._1 + y._2) btw, hence the error.

Upvotes: 3

Related Questions