Kotlin Array - indexOfLast() Function



The Kotlin array indexOfLast() function is used to return the index of the last element of the ArrayList that satisfies the given predicate. If no element matches the given predicate, then -1 is returned.

The index of last element suggests that if there are two elements with the same value, this function returns the index of the last one.

Syntax

Following is the syntax of Kotlin array indexOfLast() function −

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

Parameters

This function accepts a predicate as a parameter. Predicate represent a condition which gives boolean value.

Return value

This function returns an index of element that first satisfy the predicate from last. Otherwise; -1.

Example 1

Following is the basic example to demonstrate the use of indexOfLast() function −

fun main(args: Array<String>) {
   var list = ArrayList<Int>()
   list.add(5)
   list.add(6)
   list.add(6)
   list.add(7)
   println("The ArrayList is $list")

   var firstIndex = list.indexOfLast({it % 2 == 0 })
   println("\nThe last index of even element is $firstIndex")
}

Output

On execution of the above code we get the following result −

The ArrayList is [5, 6, 6, 7]
The last index of even element is 2

Example 2

Now, let's see another example. Here, we use the indexOfLast() function to display the index of last element having length more than 5 −

fun main(args: Array<String>) {
   // let's create an array
   var array = arrayOf("tutorialspoint", "India", "tutorix", "India")
   
   // Find the index of the first element with a length greater than 5
   val indx = array.indexOfLast { it.length > 5 }
   
   // Print the array elements
   println("Array: [${array.joinToString { "$it" }}]")
   
   if (indx != -1) {
      println("The last element with length more than 5 is at index $indx, which is \"${array[indx]}\" with length ${array[indx].length}")
   } else {
      println("No element has length more than 5.")
   }
}

Output

After execution of the above code we get the following output −

Array: [tutorialspoint, India, tutorix, India]
The last element with length more than 5 is at index 2, which is "tutorix" with length 7

Example 3

The below example creates an array. We then use indexOfLast function to display the index of the last element which is divisible by 4 −

fun main(args: Array<String>){
   // let's create an array
   var array = arrayOf<Int>(1, 2, 3, 6, 4, 5, 8)
   // using indexOfLast
   val indx = array.indexOfLast({it%4==0})
   if(indx == -1){
      println("The element is not available in the array!")
   }else{
      println("The last element which is divisible by 4 is ${array[indx]} at index: $indx")
   }
}

Output

The above code produce following output −

The last element which is divisible by 4 is 8 at index: 6
kotlin_arrays.htm
Advertisements