Kotlin Array.lastIndex

Kotlin Array.lastIndex Property

In Kotlin, the Array.lastIndex property is used to obtain the index of the last element in an array. It provides a convenient way to get the last valid index without explicitly calculating it using the array’s size.

In this tutorial, we’ll explore the syntax of the lastIndex property, how to use it to obtain the last index of an array, and provide examples of its usage in Kotlin.

Syntax

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

val lastIndex: Int = array.lastIndex

where array is the array for which to obtain the last index.

ParameterDescription
lastIndexAn Int representing the index of the last element in the array.
arrayThe array for which to obtain the last index.
Parameters of Kotlin Array lastIndex Property

Examples for Array.lastIndex Property

1. Obtaining the Last Index of an Integer Array

In this example, we’ll use the lastIndex property to obtain the index of the last element in an array of integers.

Kotlin Program

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

    // Obtaining the last index of the integer array
    val lastIndex = intArray.lastIndex

    // Printing the last index
    println("Last Index: $lastIndex")
}

Output

Last Index: 4

2. Using lastIndex for Iteration

In this example, we’ll use the lastIndex property to iterate backward over the elements of an array of characters.

Kotlin Program

fun main() {
    val charArray = arrayOf('a', 'b', 'c', 'd', 'e')

    // Iterating backward over the array using lastIndex
    for (index in charArray.lastIndex downTo 0) {
        val element = charArray[index]
        println("Element at index $index: $element")
    }
}

Output

Element at index 4: e
Element at index 3: d
Element at index 2: c
Element at index 1: b
Element at index 0: a

Summary

In this tutorial, we’ve covered the Array.lastIndex property in Kotlin arrays, its syntax, and how to use it to obtain the index of the last element.