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:
List(1, 2, 3).map(x => x + 1)
List(1, 2, 3).map(_ + 1)
But, if you do this:
List(1, 2, 3).map(_ => _ + 1)
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:
List(1, 2, 3).map(x => { y => y + 1 })
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.
If you're not going to bind an identifier, just leave that part out.
res0.map("item "+_.toString)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With