The lastIndexOf() extension function in Kotlin returns the last index of the specified element, or -1 if the set does not contain the element.
The syntax of Set.lastIndexOf() extension function is:
fun <T> Set<T>.lastIndexOf(element: T): Int
This lastIndexOf() extension function of Set returns last index of element, or -1 if the collection does not contain element.
Parameter | Optional/Required | Description |
---|---|---|
element | required | The element to search for in the set. |
Set.lastIndexOf() returns value of type Int
.
Using lastIndexOf() to find the last index of an element in a set.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5, 3)
val index = numbers.lastIndexOf(3)
println(index)
}
2
Using lastIndexOf() to find the last index of a non-existent element in a set.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val index = numbers.lastIndexOf(6)
println(index)
}
-1
Using lastIndexOf() to find the last index of a string in a set of strings.
For example,
fun main() {
val strings = setOf("a", "b", "c")
val index = strings.lastIndexOf("b")
println(index)
}
1
In this Kotlin tutorial, we learned about lastIndexOf() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.