How to get the current index in for each Kotlin

前端 未结 7 1284
Happy的楠姐
Happy的楠姐 2021-01-30 01:51

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 %          


        
相关标签:
7条回答
  • 2021-01-30 02:46

    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

    0 讨论(0)
提交回复
热议问题