问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/52415502/what-is-does-it-mean-println