1

Why I can write something like this without compilation errors:

wordCount foreach(x => println("Word: " + x._1 + ", count: " + x._2)) // wordCount - is Map

i.e. I declared the x variable.

But I can't use magic _ symbol in this case:

wordCount foreach(println("Word: " + _._1 + ", count: " + _._2)) // wordCount - is 
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286

2 Answers2

4

You should check this answer about placeholder syntax.

Two underscores mean two consecutive variables, so using println(_ + _) is a placeholder equivalent of (x, y) => println(x + y)

In first example, you just have a regular Tuple, which has accessors for first (._1) and second (._2) element.

it means that you can't use placeholder syntax when you want to reference only one variable multiple times.

Community
  • 1
  • 1
Patryk Ćwiek
  • 14,078
  • 3
  • 55
  • 76
2

Every underscore is positional. So your code is desugared to

wordCount foreach((x, y) => println("Word: " + x._1 + ", count: " + y._2))

Thanks to this, List(...).reduce(_ + _) is possible.

Moreover, since expansion is made relative to the closest paren it actually will look like:

wordCount foreach(println((x, y) => "Word: " + x._1 + ", count: " + y._2))
Community
  • 1
  • 1
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228