Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - forEach

Tags:

kotlin

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?

like image 285
Paathak Kumar Avatar asked Oct 18 '25 11:10

Paathak Kumar


1 Answers

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)
}
like image 199
s1m0nw1 Avatar answered Oct 21 '25 02:10

s1m0nw1