Kotlin Array.indexOfLast()

Kotlin Array.indexOfLast() function

In Kotlin, the Array.indexOfLast() function is used to find the index of the last element in the array that satisfies the given predicate. If no such element is found, it returns -1.

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

Syntax

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

fun <T> Array<out T>.indexOfLast(predicate: (T) -> Boolean): Int

where

ParameterDescription
predicateA lambda function that takes the element of the array as an argument and returns true or false.
Parameter of Array indexOfLast() function

The indexOfLast() function returns an Int value that represents the index of the last element in the array that satisfies the given predicate.

Examples for Array.indexOfLast() function

1. Finding the Index of the Last Even Number

In this example, we’ll use indexOfLast() to find the index of the last even number in the given array of integers numbersArray.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 3, 5, 7, 8, 9, 10, 11)

    // Finding the index of the last even number
    val indexOfLastEven = numbersArray.indexOfLast { it % 2 == 0 }

    // Printing the original array and the result
    println("Numbers Array\n${numbersArray.contentToString()}\n")
    println("Index of the last even number\n$indexOfLastEven")
}

Output

[1, 3, 5, 7, 8, 9, 10, 11]

Index of the last even number
6

Explanation

[1, 3, 5, 7, 8, 9, 10, 11]   ← given array
             *      *        ← even numbers
 0  1  2  3  4  5   6   7    ← indices
                    ↑
               indexOfLast even number

2. Finding the Index of an Element that is not in Array using indexOfLast()

In this example, we’ll use indexOfLast() in a scenario where the given array has no element that satisfies the given predicate/condition.

In the following program, the array numbersArray has no even numbers in it, and we are trying to find the index of last even number.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 3, 5, 7, 9, 11)

    // Finding the index of the last even number
    val indexOfLastEven = numbersArray.indexOfLast { it % 2 == 0 }

    // Printing the original array and the result
    println("Numbers Array\n${numbersArray.contentToString()}\n")
    println("Index of the last even number\n$indexOfLastEven")
}

Output

Numbers Array
[1, 3, 5, 7, 9, 11]

Index of the last even number
-1

Since, there is no element that matches the given predicate, Array.indexOfLast() returns -1.

Summary

In this tutorial, we’ve covered the Array.indexOfLast() function in Kotlin, its syntax, and how to use it to find the index of the last element that satisfies a given predicate.