The indexOfFirst() extension function in Kotlin returns the index of the first element matching the given predicate, or -1 if the set does not contain such an element.
The syntax of Set.indexOfFirst() extension function is:
fun <T> Set<T>.indexOfFirst(predicate: (T) -> Boolean): Int
This indexOfFirst() extension function of Set returns index of the first 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.indexOfFirst() returns value of type Int
.
Using indexOfFirst() to find the index of the first even number in a set.
For example,
fun main() {
val numbers = setOf(1, 3, 5, 6, 7, 8)
val index = numbers.indexOfFirst { it % 2 == 0 }
println(index)
}
3
Using indexOfFirst() to find the index of the first string with a length greater than 2 in a set.
For example,
fun main() {
val strings = setOf("a", "ab", "abc", "abcd")
val index = strings.indexOfFirst { it.length > 2 }
println(index)
}
2
Using indexOfFirst() to find the index of the first non-null element in a set.
For example,
fun main() {
val mixedSet: Set<Int?> = setOf(null, null, 3, 4, 5)
val index = mixedSet.indexOfFirst { it != null }
println(index)
}
2
In this Kotlin tutorial, we learned about indexOfFirst() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.