How to get the current index in for each Kotlin

Audi picture Audi · Feb 21, 2018 · Viewed 73.4k times · Source

How to get the index in a for each loop? I want to print numbers for every second iteration

For example

for (value in collection) {
    if (iteration_no % 2) {
        //do something
    }
}

In java, we have the traditional for loop

for (int i = 0; i < collection.length; i++)

How to get the i?

Answer

zsmb13 picture zsmb13 · Feb 21, 2018

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

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