Kotlin Set lastOrNull()
Syntax & Examples


Set.lastOrNull() extension function

The lastOrNull() extension function in Kotlin returns the last element in the set, or null if the set is empty. If a predicate is provided, it returns the last element that matches the given predicate, or null if no such element was found.


Syntax of Set.lastOrNull()

There are 2 variations for the syntax of Set.lastOrNull() extension function. They are:

1.
fun <T> Set<T>.lastOrNull(): T?

This extension function returns the last element, or null if the collection is empty.

Returns value of type T?.

2.
fun <T> Set<T>.lastOrNull(predicate: (T) -> Boolean): T?

Parameters

ParameterOptional/RequiredDescription
predicateoptionalA function that takes an element and returns true if the element matches the condition.

This extension function returns the last element matching the given predicate, or null if no such element was found.

Returns value of type T?.



✐ Examples

1 Getting the last element or null

Using lastOrNull() to get the last element in a set, or null if the set is empty.

For example,

  1. Create a set of integers.
  2. Use lastOrNull() to get the last element in the set.
  3. Print the resulting element or null.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val lastNumber = numbers.lastOrNull()
    println(lastNumber)
}

Output

5

2 Getting the last element or null from an empty set

Using lastOrNull() to get the last element in an empty set, or null if the set is empty.

For example,

  1. Create an empty set of integers.
  2. Use lastOrNull() to get the last element in the set.
  3. Print the resulting element or null.

Kotlin Program

fun main() {
    val emptySet = emptySet<Int>()
    val lastNumber = emptySet.lastOrNull()
    println(lastNumber)
}

Output

null

3 Getting the last even number or null

Using lastOrNull() to get the last even number in a set, or null if no even number is found.

For example,

  1. Create a set of integers.
  2. Use lastOrNull() with a predicate function that checks for even numbers.
  3. Print the resulting number or null.

Kotlin Program

fun main() {
    val numbers = setOf(1, 3, 5, 6, 7, 8)
    val lastEven = numbers.lastOrNull { it % 2 == 0 }
    println(lastEven)
}

Output

8

Summary

In this Kotlin tutorial, we learned about lastOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.