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.
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.
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes an element and returns true if the element matches the condition. |
Set.indexOfLast() returns value of type Int
.
Using indexOfLast() to find the index of the last even number in a set.
For example,
fun main() {
val numbers = setOf(1, 3, 5, 6, 7, 8)
val index = numbers.indexOfLast { it % 2 == 0 }
println(index)
}
5
Using indexOfLast() to find the index of the last string with a length greater than 2 in a set.
For example,
fun main() {
val strings = setOf("a", "ab", "abc", "abcd")
val index = strings.indexOfLast { it.length > 2 }
println(index)
}
3
Using indexOfLast() to find the index of the last non-null element in a set.
For example,
fun main() {
val mixedSet: Set<Int?> = setOf(null, 2, null, 4, null, 5)
val index = mixedSet.indexOfLast { it != null }
println(index)
}
5
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.