To iterate over a list in Kotlin with index, you can use the indices
property of the List class along with a for loop.
In this example,
numbers
with integer elements.indices
property of the list to get the range of valid indices.fun main() {
val numbers = listOf(10, 20, 30, 40, 50)
for (index in numbers.indices) {
println("Element at index $index is: ${numbers[index]}")
}
}
Element at index 0 is: 10 Element at index 1 is: 20 Element at index 2 is: 30 Element at index 3 is: 40 Element at index 4 is: 50
In this tutorial, we learned How to Iterate Over a List with Index in Kotlin language with well detailed examples.