Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current index in for each Kotlin

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?

like image 822
Audi Avatar asked Oct 04 '22 14:10

Audi


2 Answers

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

collection.forEachIndexed { index, element ->
    // ...
}
like image 589
zsmb13 Avatar answered Oct 20 '22 20:10

zsmb13


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

like image 199
Audi Avatar answered Oct 20 '22 21:10

Audi