How to use the indexOfLast() method of the ArrayList in Kotlin

The indexOfLast() method returns the index of the last element of the ArrayList that satisfies the provided Predicate functionA Predicate is a Functional interface, which takes one argument and returns either “True” or “False”, based on the defined condition.. If no element matches the provided Predicate function, then -1 is returned.

Syntax

inline fun <T> List<T>.indexOfLast(
    predicate: (T) -> Boolean
): Int

Parameter

This method takes a Predicate function as an argument.

Return value

This method returns an integer value, which denotes the last element index from the list that satisfies the provided Predicate.

If no element matches the given Predicate function, then -1 is returned.

Code example

The code written below demonstrates how we can use the indexOfLast() method:

fun main() {
var list = ArrayList<Int>()
list.add(1)
list.add(2)
list.add(3)
list.add(4)
println("The ArrayList is $list")
var lastIndex = list.indexOfLast({it % 2 == 0 })
println("\nThe last index of even element is $lastIndex")
lastIndex = list.indexOfLast({it > 4})
println("\nThe last index of element > 4 is $lastIndex")
}

Code explanation

  • Lines 3–7: We create a new ArrayList with the name list and add four elements to the list, using the add method. The list is now [1,2,3,4].

  • Line 10: We use the indexOfLast() method with a Predicate function as an argument. This function returns True if the element is even. The indexOfLast() method returns the index of the last even element. In our case, the value 3 is returned.

  • Line 13: We use the indexOfLast method with a Predicate function as an argument. This function returns True if the element is greater than 4. In our ArrayList, no element is greater than 4. Hence, the value -1 is returned.

Free Resources