Kotlin – Get First Element of Array

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

Syntax

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

arr.first()
ADVERTISEMENT

Examples

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

Main.kt

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

Output

First Element : apple

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

Main.kt

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

Output

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

Conclusion

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