Using the 'onEach' Function for Side Effects on Collections

The 'onEach' function is a useful extension function in Kotlin that allows you to perform side effects on each element of a collection without altering the original collection. This is particularly useful for logging, debugging, or any operation where you want to execute a block of code for each item while still keeping the original collection intact.

val numbers = listOf(1, 2, 3, 4, 5)

// Using onEach to print each number
numbers.onEach { number ->
    println("Number: $number")
}

// The original list remains unchanged
println("Original list: $numbers")