ForEach
This is the first terminator we'll see. Terminator functions return something other than a new collection, so you can't chain the result of this call to other calls.
In the case of forEach()
, it returns Unit. So it's like the plain, old for
loop:
val numbers = (0..5) numbers.map { it * it} // Can continue .filter { it < 20 } // Can continue .sortedDescending() // Still can .forEach { println(it) } // Cannot continue
Do note that forEach()
has some minor performance impacts compared to the traditional for
loop.
There's also forEachIndexed()
, which provides an index in the collection alongside the actual value:
numbers.map { it * it } .forEachIndexed { index, value -> print("$index:$value, ") }
The output for the preceding code will be as follows:
0:1, 1:4, 2:9, 3:16, 4:25,
Since Kotlin 1.1, there's also the onEach()
function, which is a bit more useful, since it returns the collection again:
numbers.map { it * it} .filter { it < 20 } ...