June 2018
Intermediate to advanced
310 pages
6h 32m
English
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 ...
Read now
Unlock full access