Let define a list of tuple of integer.
val as = List((1, 1), (2, 4), (3, 9))
When creating a binary function variable
f : (Int, Int) => Int, we cannot pass it directly to
as.map like this:
val f : (Int, Int) => Int = (i, j) => i + j as.map(f) /*Error */ 1 |as.map(f) | ^ | Found: (f : (Int, Int) => Int) | Required: ((Int, Int)) => Any
This is because the function required for
List[A].map must be a unary function accepting a type
A (with signature
def map[B](f: A => B): List[B]). Here
Normally, we need to convert
f like this:
as.map(f.tupled) /* Output */ val res4: List[Int] = List(2, 6, 12)
So far everything makes sense.
However, if, instead of creating a function variable, we pass a “binary” anonymous function to
map right away, it turns out that doing this produces the same result without the need to converting a function at all:
as.map((i, j) => i + j) /* Output */ val res5: List[Int] = List(2, 6, 12)
What are mechanisms behind this behavior?