Kotlin – Get first element in Array

Get first element in Array in Kotlin

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

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

arr.first()

A simple example with an input and desired output is

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

First element
"apple"

Examples

Get first element from given Array

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

Kotlin Program

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

Output

apple