Kotlin – Get last element in Array

Get last element in Array in Kotlin

To get the last element from the Array in Kotlin, you can use Array.last() function.

Call the last() function on the given Array object, and the function returns the last element.

arr.last()

A simple example with an input and desired output is

Input Array
["apple", "banana", "cherry", "mango"]

Last element
"mango"

Examples

Get last element from given Array

In the following program, we take an Array of strings in arr, and fetch the last element from the Array.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf<String>("apple", "banana", "cherry", "mango")
    val lastElement = arr.last()
    println(lastElement)
}

Output

mango