Kotlin Array last()
In Kotlin, the Array last()
function is used to obtain the last element of the given array that satisfies a given predicate. It returns the last element that matches the predicate or throws a NoSuchElementException
if no such element is found.
If no predicate is given, then last()
function returns the last element in the array.
In this tutorial, we’ll explore the syntax of the last()
function and provide examples of its usage in Kotlin arrays, both with and without a predicate.
Syntax
The syntax of the last()
function is as follows:
fun <T> Array<out T>.last(): T
fun <T> Array<out T>.last(predicate: (T) -> Boolean): T
where
Parameter | Description |
---|---|
predicate | A lambda function that takes the element of array as argument and returns true or false . |
If no element satisfies the predicate or if the array is empty, the function throws a NoSuchElementException
.
Examples for Array last() function
1. Using last() with a Predicate
In this example, we’ll use last()
with a predicate to obtain the last even number from an array of integers.
Kotlin Program
fun main() {
val numbersArray = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
// Using last() with a predicate to obtain the last even number
val lastEvenNumber = numbersArray.last { it % 2 == 0 }
// Printing the original array and the result
println("Numbers Array: \n${numbersArray.joinToString(", ")}\n")
println("Last Even Number: $lastEvenNumber")
}
Output
Numbers Array:
1, 2, 3, 4, 5, 6, 7, 8, 9
Last Even Number: 8
2. Using last() without a Predicate
In this example, we’ll use last()
without a predicate to obtain the last element of an array of numbers.
Kotlin Program
fun main() {
val numbersArray = arrayOf(1, 2, 3, 4, 5, 3, 6, 7, 8, 9)
// Using last() without a predicate to obtain the last element
val lastElement = numbersArray.last()
// Printing the original array and the result
println("Numbers Array: \n${numbersArray.joinToString(", ")}\n")
println("Last Element: $lastElement")
}
Output
Numbers Array:
1, 2, 3, 4, 5, 3, 6, 7, 8, 9
Last Element: 9
3. Using last() with an Empty Array
In this example, we’ll use last()
with an empty array to demonstrate the NoSuchElementException
when the array is empty.
Kotlin Program
fun main() {
val numbersArray = intArrayOf()
// Using last() to obtain the last element
val firstElement = numbersArray.last()
println("Last Element : $firstElement")
}
Output
Exception in thread "main" java.util.NoSuchElementException: Array is empty.
at kotlin.collections.ArraysKt___ArraysKt.last(_Arrays.kt:1887)
at MainKt.main(Main.kt:5)
at MainKt.main(Main.kt)
You may use a try-catch block to handle this exception.
Summary
In this tutorial, we’ve covered the last()
function in Kotlin arrays, its syntax, and how to use it to obtain the last element based on a predicate. Remember to handle the NoSuchElementException
when using this function to prevent runtime errors.