1

I have this piece of code in scala

val wordCounts = logData.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey((a, b) => a + b)
wordCounts.foreach(println(_))

So what does println(_) mean and what should it print?

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
Khaled
  • 345
  • 5
  • 14
  • you will find what `_` mean: [What are all the uses of an underscore in Scala?](https://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala). Your code is equivalnet to `wordCounts.foreach(x => println(x)) `, where `_` represent each element – prayagupa Sep 19 '18 at 23:34
  • @prayagupd I've already tried to use this Q/A as duplicate target today, the last questioner didn't like it: too much unrelated stuff, had to reopen... :/ – Andrey Tyukin Sep 19 '18 at 23:37

1 Answers1

2

As explained in the section "Placeholder Syntax for Anonymous Functions" of the Spec,

println(_)

is a shortcut for the anonymous function literal

w => println(w)

which in turn is a shortcut for something like

(w: (String, Int)) => println(w)

in this particular case.

Therefore,

wordCounts.foreach(println(_))

simply prints every element of wordCounts.

Note that it can also be written even shorter:

wordCounts foreach println
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93