Kotlin – forEach

我是Kotlin的初学者。 你如何解释下面的代码片段?

fun main(args: Array<String>) { var k = listOf<Double>(1.2,77.8,6.3,988.88,0.1) k.forEach(::println) } 

这运行良好,并给出了名单,但有人可以请帮助解释如何k.forEach(:: println)真的工作?

forEachk每个元素都做了,并且做了你所说的。 在你的例子中,“what”参数是::println ,它引用了stdlib函数println(message: Any)::引入了这个函数的函数引用 。 每个元素都作为参数messageprintln ,因此它被打印在控制台上。

为了使它更清楚,你可以传递一个lambda而不是函数引用,像这样:

 k.forEach{ println(it) } 

内联乐趣Iterable.forEach(action:(T) – > Unit)

public inline fun Iterable.forEach(action:(T) – > Unit):Unit {for(element in this)action(element)}