How to get the current index in for each Kotlin

Solution 1:

In addition to the solutions provided by @Audi, there's also forEachIndexed:

collection.forEachIndexed { index, element ->
    // ...
}

Solution 2:

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

Solution 3:

Alternatively, you can use the withIndex library function:

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

Control Flow: if, when, for, while: https://kotlinlang.org/docs/reference/control-flow.html

Solution 4:

try this; for loop

for ((i, item) in arrayList.withIndex()) { }

Solution 5:

Working Example of forEachIndexed in Android

Iterate with Index

itemList.forEachIndexed{index, item -> 
println("index = $index, item = $item ")
}

Update List using Index

itemList.forEachIndexed{ index, item -> item.isSelected= position==index}