Skip to content

Instantly share code, notes, and snippets.

@amay077
Created December 6, 2017 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amay077/7c79938678d5f43e8df6723e65742831 to your computer and use it in GitHub Desktop.
Save amay077/7c79938678d5f43e8df6723e65742831 to your computer and use it in GitHub Desktop.
firstIndexOrNull in Kotlin collections
inline fun <T> Iterable<T>.firstIndexOrNull(predicate: (T) -> Boolean): Int? {
return this.mapIndexed { index, place -> Pair(index, place) }
.firstOrNull() { predicate(it.second) }
?.first
}
val arr = arrayListOf("a", "b", "c")
arr.firstIndexOrNull { it == "b"} // -> 1
arr.firstIndexOrNull { it == "z"} // -> null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment