Kotlin List last()
Syntax & Examples
Syntax of List.last()
There are 2 variations for the syntax of List.last() extension function. They are:
1.
fun <T> List<T>.last(): T
This extension function returns the last element.
2.
fun <T> List<T>.last(predicate: (T) -> Boolean): T
This extension function returns the last element matching the given predicate.
✐ Examples
1 Example
In this example,
- We create a list of strings named
list
containing elements"apple", "banana", "cherry"
. - We use the
last()
function to get the last element of the list, which is"cherry"
. - Finally, we print the last element to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry")
val lastElement = list.last()
println("Last element: \$lastElement")
}
Output
Last element: cherry
2 Example
In this example,
- We create a list of characters named
list
containing elements'a', 'b', 'c', 'd', 'e'
. - We use the
last()
function to get the last element of the list, which is'e'
. - Finally, we print the last element to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e')
val lastElement = list.last()
println("Last element: \$lastElement")
}
Output
Last element: e
3 Example
In this example,
- We create a list of strings named
list
containing elements"red", "green", "blue"
. - We use the
last()
function to get the last element of the list, which is"blue"
. - Finally, we print the last element to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("red", "green", "blue")
val lastElement = list.last()
println("Last element: \$lastElement")
}
Output
Last element: blue
Summary
In this Kotlin tutorial, we learned about last() extension function of List: the syntax and few working examples with output and detailed explanation for each example.