Extension method
inline fun <T> Iterable<T>.firstIndexOrNull(predicate: (T) -> Boolean): Int? {
return this.mapIndexed { index, item -> Pair(index, item) }
.firstOrNull() { predicate(it.second) }
?.first
}
Just using .mapIndexed
and .firstOrNull
.
Usage
val arr = arrayListOf("a", "b", "c")
arr.firstIndexOrNull { it == "b"} // -> 1
arr.firstIndexOrNull { it == "z"} // -> null
Top comments (1)
There's no need to manually go over the list using
mapIndexed
. Instead, you should use the built-in indexOfFirst extension function.