println(_)是什么意思? [英] what is does it mean println(_)?

查看:56
本文介绍了println(_)是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在scala中有这段代码

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(_))

那么println(_)是什么意思,应该打印什么?

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

推荐答案

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)

在这种情况下.

因此

wordCounts.foreach(println(_))

仅打印 wordCounts 的每个元素.

请注意,它也可以写得更短:

Note that it can also be written even shorter:

wordCounts foreach println

这篇关于println(_)是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆