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)
res14: List[Int] = List(3, 4, 5, 6)
res15: List[Int] = List(3, 4, 5, 6)
res16: List[Int] = List(1, 2, 3, 4)
<console>:13: error: missing parameter type for expanded function ((x$1) => list.map(x$1))
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(_), 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)