Kotlin – Get Last Element of Array

To get the last element of an Array in Kotlin language, use Array.last() method. Call last() method on this array, and the method returns the last element.

Syntax

The syntax to call last() method on Array arr is

arr.last()
ADVERTISEMENT

Examples

In the following program, we take an array of strings, and get the last element of this array using Array.last() method.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana")
    val element = arr.last()
    println("Last Element : $element")
}

Output

Last Element : banana

Now, let us take an empty array, and check the result of last() method on this array.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf<String>()
    val element = arr.last()
    println("Last Element : $element")
}

Output

Exception in thread "main" java.util.NoSuchElementException: Array is empty.
	at kotlin.collections.ArraysKt___ArraysKt.last(_Arrays.kt:1841)
	at MainKt.main(Main.kt:3)

Conclusion

In this Kotlin Tutorial, we learned how to get the last element of given array, using Array.last() method, in Kotlin programming language with examples.