简体   繁体   English

科特林-forEach

[英]Kotlin - forEach

I am beginner in Kotlin. 我是科特林的初学者。 How do you explain the following code snippet ? 您如何解释以下代码片段?

fun main(args: Array<String>) {

    var k = listOf<Double>(1.2,77.8,6.3,988.88,0.1)

        k.forEach(::println)
}

This runs fine and gives the list but can someone please help with the explanation for how does k.forEach(::println) really work? 这样可以很好地运行并给出列表,但是有人可以帮忙解释一下k.forEach(:: println)实际如何工作吗?

forEach takes each element in k and does what you specify it to do. forEach发生在每个元素k并没有指定它做什么 In your example, the " what " argument is ::println , which refers to the stdlib function println(message: Any) . 在您的示例中,“ what ”参数是::println ,它表示stdlib函数println(message: Any) The :: introduced a function reference to this function. ::引入了对此函数的函数引用 Each element is passed as the argument message to println and thus it's being printed on the console. 每个元素都作为参数messageprintln ,因此将其打印在控制台上。

To make it more clear, you could pass a lambda instead of the function reference like this: 为了更加清楚,您可以传递lambda而不是像这样的函数引用:

k.forEach{
   println(it)
}

inline fun Iterable.forEach(action: (T) -> Unit) 内联乐趣Iterable.forEach(action:(T)-> Unit)

public inline fun Iterable.forEach(action: (T) -> Unit): Unit { for (element in this) action(element) } public inline fun Iterable.forEach(action:(T)-> Unit):Unit {代表(此元素)action(element)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM