Kotlin Array - lastIndexOf() Function



The Kotlin array lastIndexOf() function is used to return the index of the last occurrence of the specified element, or -1 if the array does not contain element.

For example; if we have an array like [1, 2, 3, 1], calling lastIndexOf(1) would return 3, as it is the index of the last occurrence of 1.

Syntax

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

fun <T> Array<out T>.lastIndexOf(element: T): Int

Parameters

This function accepts an element as a parameter whose index needs to be searched.

Return value

This function returns an index. Otherwise; -1.

Example 1

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

fun main(args: Array<String>) {
   val array = arrayOf<Int>(1, 2, 3, 1)
   val indx = array.lastIndexOf(1)
   println("last index of ${array[indx]}: $indx")
}

Output

On execution of the above code we get following output −

last index of 1: 3

Example 2

The example created an array of characters. We then use lastIndexOf function to get the last index of specified char −

fun main(args: Array<String>) {
   val array = arrayOf<Char>('a', 'b', 'c', 'd', 'e')
   val indx = array.lastIndexOf('c')
   println("last index of ${array[indx]}: $indx")
}

Output

Following is the output −

last index of c: 2

Example 3

The below example finds the last index of the specified element. If the element is not available then lastIndexOf returns -1 −

fun main(args: Array<String>) {
   val array = arrayOf<String>("tutorialspoint", "India")
   // check the last index
   val lastIndx = array.lastIndexOf("hello")
   print("The last index of hello: $lastIndx") 
}

Output

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

The last index of hello: -1
kotlin_arrays.htm
Advertisements