lastOrNull
LastOrNull is a Kotlin standard library function that returns the last element of an iterable or a sequence, or null if the collection is empty. It is available as an extension on Iterable<T> and Sequence<T>, and there is an overload that accepts a predicate. This makes it the null-safe counterpart to last, which throws an exception when no element is found.
Without a predicate, lastOrNull traverses the collection or sequence to obtain its last element. For lists
Return type and null safety: the function returns a value of type T? (nullable). This supports safe
nums.lastOrNull { it > 2 } // 3
- val empty = emptyList<Int>()
- last() returns the last element but throws NoSuchElementException if the collection is empty.
- lastOrNull() returns null instead of throwing, optionally applying a predicate to filter candidates.
See also: firstOrNull, first, last, lastOrNull with a predicate.