Created
December 6, 2017 05:58
-
-
Save amay077/7c79938678d5f43e8df6723e65742831 to your computer and use it in GitHub Desktop.
firstIndexOrNull in Kotlin collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun <T> Iterable<T>.firstIndexOrNull(predicate: (T) -> Boolean): Int? { | |
return this.mapIndexed { index, place -> Pair(index, place) } | |
.firstOrNull() { predicate(it.second) } | |
?.first | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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