Paathak Kumar
Paathak Kumar

Reputation: 65

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?

Upvotes: 4

Views: 3658

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81879

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)
}

Upvotes: 8

user8320224
user8320224

Reputation: 228

inline fun Iterable.forEach(action: (T) -> Unit)

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

Upvotes: -2

Related Questions