Kotlin Array.indices

Kotlin Array.indices Property

In Kotlin, the Array.indices property is used to obtain a range representing the valid indices of an array.

It provides a convenient way to iterate over all valid indices of the array without explicitly specifying the range boundaries.

In this tutorial, we’ll explore the syntax of the Array.indices property, how to use it to iterate over array elements, and provide examples of its usage in Kotlin.

Syntax

The syntax of the Array.indices property is as follows:

val arrayIndices: IntRange = array.indices

where array is the array for which to obtain the indices.

Examples for Array.indices Property

1. Iterating Over an Integer Array using indices

In this example, we’ll use the indices property to iterate over the valid indices of an array of integers and access the corresponding elements.

Kotlin Program

fun main() {
    val intArray = intArrayOf(10, 20, 30, 40, 50)

    // Iterating over the array using indices
    for (index in intArray.indices) {
        val element = intArray[index]
        println("Element at index $index: $element")
    }
}

Output

Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

2. Updating Elements Using indices

In this example, we’ll use the indices property to update elements in an array of doubles based on the valid indices.

Kotlin Program

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

    // Updating elements using indices
    for (index in intArray.indices) {
        intArray[index] *= 2
    }

    // Printing the updated array
    println("Updated Array\n${intArray.contentToString()}")
}

Output

Updated Array
[20, 40, 60, 80, 100]

Summary

In this tutorial, we’ve covered the Array.indices property in Kotlin, its syntax, and how to use it to obtain a range representing the valid indices of the array.