Kotlin List lastOrNull()
Syntax & Examples
Syntax of List.lastOrNull()
There are 2 variations for the syntax of List.lastOrNull() extension function. They are:
1.
fun <T> List<T>.lastOrNull(): T?
This extension function returns the last element, or null if the list is empty.
2.
fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T?
This extension function returns the last element matching the given predicate, or null if no such element was found.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing strings'apple', 'banana', 'orange'
. - We use the
lastOrNull()
function to retrieve the last element oflist
. - Since the list is not empty, the last element is returned.
- Finally, we print the last element to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "orange");
val lastElement = list.lastOrNull();
println("Last element: \$lastElement");
}
Output
Last element: orange
2 Example
In this example,
- We create a list named
list
containing characters'a', 'b', 'c'
. - We use the
lastOrNull()
function to retrieve the last element oflist
. - Since the list is not empty, the last element is returned.
- Finally, we print the last element to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c');
val lastElement = list.lastOrNull();
println("Last element: \$lastElement");
}
Output
Last element: c
3 Example
In this example,
- We create a list named
list
containing strings'one', 'two', 'three'
. - We use the
lastOrNull()
function with a predicate to find the last element with a length greater than 10. - Since there is no element in the list with a length greater than 10,
null
is returned. - Finally, we print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("one", "two", "three");
val lastElement = list.lastOrNull { it.length > 10 };
println("Last element with length greater than 10: \$lastElement");
}
Output
Last element with length greater than 10: null
Summary
In this Kotlin tutorial, we learned about lastOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.