To get the first element of an array in Kotlin, you can use the indexing notation with square brackets and the index 0.
In this example,
numbers
with integer values.numbers[0]
and store it in a variable named firstElement
.fun main() {
val numbers = intArrayOf(10, 20, 30, 40, 50)
val firstElement = numbers[0]
println("First element: $firstElement")
}
First element: 10
In this example,
fruits
with string values.fruits[0]
and store it in a variable named firstFruit
.fun main() {
val fruits = arrayOf("Apple", "Banana", "Cherry", "Date")
val firstFruit = fruits[0]
println("First fruit: $firstFruit")
}
First fruit: Apple
In this tutorial, we learned How to get First Element in Array in Kotlin language with well detailed examples.