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:
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?
.
fun <T> Set<T>.lastOrNull(predicate: (T) -> Boolean): T?
Parameters
Parameter | Optional/Required | Description |
---|---|---|
predicate | optional | A 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,
- Create a set of integers.
- Use lastOrNull() to get the last element in the set.
- 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,
- Create an empty set of integers.
- Use lastOrNull() to get the last element in the set.
- 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,
- Create a set of integers.
- Use lastOrNull() with a predicate function that checks for even numbers.
- 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.