To get the first element in a Kotlin List, you can use the get method with index 0.
In this example,
numbers
with integer elements.get
method with index 0.get
method returns the element at the specified index.fun main() {
val numbers = listOf(10, 20, 30, 40, 50)
val firstElement = numbers.get(0)
println("First element is: $firstElement")
}
First element is: 10
In this example,
names
with string elements.get
method with index 0.get
method returns the element at the specified index.fun main() {
val names = listOf("Alice", "Bob", "Charlie", "David")
val firstElement = names.get(0)
println("First element is: $firstElement")
}
First element is: Alice
In this tutorial, we learned How to get First Element in a List in Kotlin language with well detailed examples.