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?
forEach
takes each element in k
and does what you specify it to do. In your example, the "what" argument is ::println
, which refers to the stdlib function 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.
To make it more clear, you could pass a lambda instead of the function reference like this:
k.forEach{
println(it)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With