Skip to content

Instantly share code, notes, and snippets.

@sonique6784
Last active February 16, 2023 21:37
Show Gist options
  • Save sonique6784/6c6bb15306ad9d7248542b9b9465362a to your computer and use it in GitHub Desktop.
Save sonique6784/6c6bb15306ad9d7248542b9b9465362a to your computer and use it in GitHub Desktop.
kotlin findLastIndex() extension function
// https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/kotlin/collections/Collections.kt
/**
* Returns the index of the last item in the list that match predicate
* @param predicate function returning boolean for matching element.
*
* @return the index of the last element found
* otherwise returns -1
*/
public inline fun <T> List<T>.findLastIndex(predicate: (T) -> Boolean): Int {
val iterator = this.listIterator(size)
var count = 1
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return size - count
count++
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment