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

标签 android for-loop kotlin

如何在 for each 循环中获取索引?我想为每第二次迭代打印一次数字

例如

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

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

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

如何获取i

最佳答案

除了@Audi提供的解决方案,还有forEachIndexed :

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

关于android - 如何获取每个 Kotlin 的当前索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48898102/

相关文章:

java - 单击按钮时创建 EditText

android - Android 上的方位角/偏航和滚动方向传感器值不一致

javascript - 使用 for 循环将 3 个函数合并为一个函数

android - 期望意外类型的 Kotlin 泛型

android - 如何在 Android 中为字符设备驱动程序创 build 备节点?

android - 迁移 Firestore 替换字段

.net - 用自定义 VBA 类包装 .Net ArrayList 获取迭代器

python - 如何在 python 数据帧中的确定行之后添加一个空行?

android - Kotlin 如何通过 lambda 使用自定义点击监听器而不是声明对象 : CustomClass

Android Facebook登录失败无异常,只是 "Sorry something went wrong"