Home

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

Examples:

- val nums = listOf(1, 2, 3)

nums.lastOrNull() // 3

nums.lastOrNull { it > 2 } // 3

- val empty = emptyList<Int>()

empty.lastOrNull() // null

Comparison with last:

- 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.

with
efficient
random
access,
implementations
may
optimize,
but
for
sequences
it
must
process
elements
in
order
until
the
end.
If
the
collection
has
no
elements,
the
function
returns
null.
With
a
predicate,
lastOrNull
returns
the
last
element
that
satisfies
the
predicate,
or
null
if
none
do.
calls
and
the
Elvis
operator,
for
example:
list.lastOrNull()
?:
defaultValue
or
list.lastOrNull()?.let
{
…
}.