Kotlin Array.withIndex()

Kotlin Array.withIndex() function

In Kotlin, the Array.withIndex() function is used to obtain an iterable of indexed elements. It returns an iterable of IndexedValue elements, where each element is a pair containing the index and the corresponding value from the original array.

This function is particularly useful when you need to iterate over an array and access both the index and the value of each element simultaneously.

In this tutorial, we’ll explore the syntax of the Array.withIndex() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of Array.withIndex() function is:

fun <T> Array<out T>.withIndex(): Iterable<IndexedValue<T>>

The withIndex() function returns an iterable of IndexedValue elements, where each IndexedValue has the properties index and value representing the index and value of the original array, respectively.

Examples for Array.withIndex() function

1. Iterating over Elements with Indices

In this example, we’ll use withIndex() to iterate over elements in an array fruitsArray along with their indices.

Kotlin Program

fun main() {
    val fruitsArray = arrayOf("Apple", "Banana", "Cherry")

    // Iterating over elements with indices using withIndex()
    for ((index, value) in fruitsArray.withIndex()) {
        println("Index: $index, Value: $value")
    }
}

Output

Index: 0, Value: Apple
Index: 1, Value: Banana
Index: 2, Value: Cherry

2. Using Indices to Manipulate Array Elements

In this example, we’ll use withIndex() to access both the index and value of each element and manipulate the array elements accordingly. We shall double the values in the array at even indices.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40)
    println("Given Array\n${numbersArray.contentToString()}")

    // Doubling the value of each element at even indices
    for ((index, value) in numbersArray.withIndex()) {
        if (index % 2 == 0) {
            numbersArray[index] = value * 2
        }
    }

    // Printing the modified array
    println("Modified Array\n${numbersArray.contentToString()}")
}

Output

Given Array
[10, 20, 30, 40]
Modified Array
[20, 20, 60, 40]

Summary

In this tutorial, we’ve covered the withIndex() function in Kotlin arrays, its syntax, and how to use it to iterate over elements with their indices. This function is especially handy when you need both the index and value of array elements during iteration for various operations.