Kotlin Tutorials

Kotlin Set indexOfLast()
Syntax & Examples

Set.indexOfLast() extension function

The indexOfLast() extension function in Kotlin returns the index of the last element matching the given predicate, or -1 if the set does not contain such an element.


Syntax of Set.indexOfLast()

The syntax of Set.indexOfLast() extension function is:

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

This indexOfLast() extension function of Set returns index of the last element matching the given predicate, or -1 if the collection does not contain such element.

Parameters

ParameterOptional/RequiredDescription
predicaterequiredA function that takes an element and returns true if the element matches the condition.

Return Type

Set.indexOfLast() returns value of type Int.



✐ Examples

1 Finding the index of the last even number

Using indexOfLast() to find the index of the last even number in a set.

For example,

  1. Create a set of integers.
  2. Use indexOfLast() with a predicate function that checks for even numbers.
  3. Print the resulting index.

Kotlin Program

fun main() {
    val numbers = setOf(1, 3, 5, 6, 7, 8)
    val index = numbers.indexOfLast { it % 2 == 0 }
    println(index)
}

Output

5

2 Finding the index of the last string with length greater than 2

Using indexOfLast() to find the index of the last string with a length greater than 2 in a set.

For example,

  1. Create a set of strings.
  2. Use indexOfLast() with a predicate function that checks for strings with a length greater than 2.
  3. Print the resulting index.

Kotlin Program

fun main() {
    val strings = setOf("a", "ab", "abc", "abcd")
    val index = strings.indexOfLast { it.length > 2 }
    println(index)
}

Output

3

3 Finding the index of the last non-null element

Using indexOfLast() to find the index of the last non-null element in a set.

For example,

  1. Create a set containing integers and null values.
  2. Use indexOfLast() with a predicate function that checks for non-null values.
  3. Print the resulting index.

Kotlin Program

fun main() {
    val mixedSet: Set<Int?> = setOf(null, 2, null, 4, null, 5)
    val index = mixedSet.indexOfLast { it != null }
    println(index)
}

Output

5

Summary

In this Kotlin tutorial, we learned about indexOfLast() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.