Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, what is the difference between using the `_` and using a named identifier?

Tags:

scala

wildcard

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)
like image 288
Scoobie Avatar asked Mar 01 '10 00:03

Scoobie


2 Answers

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.

like image 108
David Winslow Avatar answered Nov 18 '22 06:11

David Winslow


If you're not going to bind an identifier, just leave that part out.

res0.map("item "+_.toString)
like image 29
Mitch Blevins Avatar answered Nov 18 '22 08:11

Mitch Blevins