Manu Chadha Manu Chadha - 14 days ago 6
Scala Question

need clarity about use of single underscore only in scala

not able to type underscore in question. The code snippet has underscore though.

why list.map(+2) works in place of list.map(x=>x+2) but list.map() doesnt work in place of list.map(x=>x)?

scala> val list = List(1,2,3,4)
list: List[Int] = List(1, 2, 3, 4)

scala> list.map(_+2)
res14: List[Int] = List(3, 4, 5, 6)

scala> list.map(x=>x+2)
res15: List[Int] = List(3, 4, 5, 6)

scala> list.map(x=>x)
res16: List[Int] = List(1, 2, 3, 4)

scala> list.map(_)
<console>:13: error: missing parameter type for expanded function ((x$1) => list.map(x$1))
list.map(_)
^

scala>

Answer

It's pretty simple. If _ was considered a valid expression for anonymous function and translated to x => x, then _ * 2 would be translated to (x => x) * 2, which would make placeholders useless. Instead Scala is trying to find the first complete expression going "outwards" from _. In case of list.map(_) it's list.map(_), so you have x => list.map(x).

More interesting examples:

_ + (2 * _) //> x => x + (y => 2 * y)
_ + 2 * _   //> (x, y) => x + 2 * y

(parentheses "complete" expression)

Comments