The forEach and onEach functions

The forEach function was discussed in the chapter about functions. It is an alternative to a for loop, so it performs an action on each element of the list:

    listOf("A", "B", "C").forEach { print(it) } // prints: ABC 

Since Kotlin 1.1, there is a similar function, onEach, that also invokes an action on each element. It returns an extension receiver so we can invoke an action on each element in the middle of stream processing. This is commonly used for logging purposes. Here is an example:

 
    (1..10).filter { it % 3 == 0 } 
       .onEach(::print) // Prints: 369 
       .map { it / 3 } 
       .forEach(::print) // Prints: 123 

Get Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.