Why do i get an error when I try using _ instead of using a named identifier?
scala> res0
res25: List[Int] = List(1, 2, 3, 4, 5)
scala> res0.map(_=>"item "+_.toString)
<console>:6: error: missing parameter type for expanded function ((x$2) => "item
".$plus(x$2.toString))
res0.map(_=>"item "+_.toString)
^
scala> res0.map(i=>"item "+i.toString)
res29: List[java.lang.String] = List(item 1, item 2, item 3, item 4, item 5)
Underscores used in place of variable names like that are special; the Nth underscore means the Nth argument to an anonymous function. So the following are equivalent:
But, if you do this:
Then you are mapping the list with a function that ignores its single argument and returns the function defined by
_ + 1. (This specific example won’t compile because the compiler can’t infer what type the second underscore has.) An equivalent example with named parameters would look like:In short, using underscores in a function’s argument list means “I am ignoring these arguments in the body of this function.” Using them in the body means “Compiler, please generate an argument list for me.” The two usages don’t mix very well.