如何获取每个 Kotlin 的当前索引

2024-04-01

如何在foreach循环中获取索引?我想打印每第二次迭代的数字

例如

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

在java中,我们有传统的for循环

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

如何获得i?


除了@Audi提供的解决方案之外,还有forEachIndexed https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/for-each-indexed.html:

collection.forEachIndexed { index, element ->
    // ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何获取每个 Kotlin 的当前索引 的相关文章