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 -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
listand add four elements to thelist, using theaddmethod. The list is now[1,2,3,4]. -
Line 10: We use the
indexOfLast()method with a Predicate function as an argument. This function returnsTrueif the element is even. TheindexOfLast()method returns the index of the last even element. In our case, the value3is returned. -
Line 13: We use the
indexOfLastmethod with a Predicate function as an argument. This function returnsTrueif the element is greater than4. In ourArrayList, no element is greater than4. Hence, the value-1is returned.