Kotlin Array.forEachIndexed()

Kotlin Array.forEachIndexed() Tutorial

The Array.forEachIndexed() function in Kotlin is used to iterate over the elements of an array along with their indices. It executes the specified action for each element, providing both the index and the element as parameters to the action.

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

Syntax

The syntax of the forEachIndexed() function is as follows:

inline fun <T> Array<out T>.forEachIndexed(action: (index: Int, T) -> Unit): Unit

where

ParameterDescription
actionFunction that takes the index of an element and the element itself and performs the action on the element.
Parameters of Array.forEachIndexed()

Examples for Array.forEachIndexed() function

1. Iterate over Array, and print index, element

In this example, we’ll use the forEachIndexed() function to iterate over an array of integers numbersArray, printing both the index and the value of each element.

Kotlin Program

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

    // Using forEachIndexed() to print index and value of each element
    numbersArray.forEachIndexed { index, value ->
        println("Index: $index, Value: $value")
    }
}

Output

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50

Summary

In this tutorial, we’ve covered the forEachIndexed() function in Kotlin arrays, its syntax, and how to use it to iterate over array elements with their corresponding indices. This function is useful when you need to perform actions on both the index and the value during array traversal.