what is does it mean println(_)?

帅比萌擦擦* 提交于 2019-12-11 11:23:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!