To get the last element in an array in Kotlin, you can use the last()
method of the Array class.
In this example,
numbers
with some elements.last()
method of the array object numbers
to get the last element and store it in the variable lastElement
.last()
method returns the last element of the array.lastElement
to the console.fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
val lastElement = numbers.last()
println("Last element is: $lastElement")
}
Last element is: 5
In this example,
fruits
with some elements.last()
method of the array object fruits
to get the last element and store it in the variable lastFruit
.last()
method returns the last element of the array.lastFruit
to the console.fun main() {
val fruits = arrayOf("Apple", "Banana", "Cherry")
val lastFruit = fruits.last()
println("Last fruit is: $lastFruit")
}
Last fruit is: Cherry
In this tutorial, we learned How to get Last Element in Array in Kotlin language with well detailed examples.