lastOrNull

public fun <T> List<T>.lastOrNull(): T? {
    return if (isEmpty()) null else this[size - 1]
}

val list = listOf(1, 2, 3, 4, 5)
println(list.lastOrNull())  // 5
println(listOf<Int>().lastOrNull())  // null

public inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? {
    val iterator = this.listIterator(size)
    while (iterator.hasPrevious()) {
        val element = iterator.previous()
        if (predicate(element)) return element
    }
    return null
}

val list = listOf(1, 2, 3, 4, 5)
println(list.lastOrNull{ it > 3 })  // 5
println(list.lastOrNull{ it > 7 })  // null

Last updated