Kotlin Array.onEach()

Kotlin Array.onEach() Tutorial

In Kotlin, the Array.onEach() function is used to perform an action for each element of the array without modifying the original array. It is particularly useful for performing side effects, such as logging or printing, while iterating through the elements.

This tutorial will explore the syntax of the Array.onEach() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.onEach() function is as follows:

fun <T> Array<out T>.onEach(
    action: (T) -> Unit
): Array<T>

where

ParameterDescription
actionA lambda function that takes an element of the array as an argument and performs an action on it.
Parameter of Array.onEach() function

Examples for Array.onEach() function

1. Using onEach() for Logging

In this example, we’ll use the onEach() function to log each element of an array. Logging means printing to console output in this example. You may print the element to a log file if you want.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40, 50)

    // Using onEach() for logging each element
    numbersArray.onEach { println("Processing element: $it") }
}

Output

Processing element: 10
Processing element: 20
Processing element: 30
Processing element: 40
Processing element: 50

2. Using onEach() to Update External State

In this example, we’ll use the onEach() function to update an external state while iterating through the elements of the array.

Here we are iterating to find the sum of elements in the given array of integers, and the external state is the sum variable.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40, 50)
    var sum = 0

    // Using onEach() to update the sum while iterating
    numbersArray.onEach { sum += it }

    // Printing the original array and the updated sum
    println("Numbers Array:\n${numbersArray.contentToString()}\n")
    println("Sum of Numbers:\n$sum")
}

Output

Numbers Array:
[10, 20, 30, 40, 50]

Sum of Numbers:
150

Summary

In this tutorial, we’ve covered the onEach() function in Kotlin arrays, its syntax, and how to use it to perform actions on each element of the array without modifying the array itself. Remember that onEach() is designed for side effects and does not change the original array.