How to get the current index in for each Kotlin
Use indices
for (i in array.indices) {
print(array[i])
}
If you want value as well as index Use withIndex()
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
Reference: Control-flow in kotlin
In addition to the solutions provided by @Audi, there's also forEachIndexed
:
collection.forEachIndexed { index, element ->
// ...
}