3

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>
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
  • 1
    Underscores, in Scala, [can be confusing](http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala). – jwvh Nov 17 '16 at 22:50

3 Answers3

2

For this you need to use the identity function. That's because in this case, the placeholder _ makes your expression list.map(_) a partially applied function. Maybe it makes it clearer if you assign it to a val:

val fun: (Int => Int) => List[Int] = list.map(_)

You could then use your val fun like so:

fun(_ * 2) // returns List(2, 4, 6, 8)

If you want to map to the same value, you can use identity:

list.map(identity) // returns List(1, 2, 3, 4)
Zoltán
  • 21,321
  • 14
  • 93
  • 134
2

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)

Victor Moroz
  • 9,167
  • 1
  • 19
  • 23
0

The _ in what you're describing is placeholder syntax for anonymous functions and represents an argument to a function.

E.g:

list.map(_+2) // map takes a function which takes one argument and returns that arg + 2

Since map takes a function as an argument, and not a placeholder, that is why you're seeing this issue.

Community
  • 1
  • 1
David Weiser
  • 5,190
  • 4
  • 28
  • 35