Kotlin for循环
我试图学习kotlin语言(特别是对于android),但我发现学习各种for循环有一些困难,所以正常循环,每个循环和每个索引,以及如何使用它有什么区别?
例如在这篇文章中: https : //medium.com/mindorks/building-a-customview-tictactoe-eb439f506505 (即谈到android自定义视图),有这个部分:
squares.forEachIndexed { i, rects -> for ((j, rect) in rects.withIndex()) { if (rect.contains(x.toInt(), y.toInt())) return Pair(i, j) } }
在那里他使用每个索引遍历所有包含在正方形(即2d数组)的variables,但我真的不明白它是如何工作的。 感谢任何帮助我的人!
这里有一些选择:
-
使用
forEachIndexed
:myList.forEachIndexed { i, element -> println(i) println(element) }
-
带
withIndex
的扩展types可用于for
each:val ints = arrayListOf(1, 2, 3, 4, 5) for ((i, e) in ints.withIndex()) { println("$i: $e") }
-
然后在
Collection
,Array
等等上有一个扩展属性indices
,这个indices
从C,Java等已知的常见for
:for(i in ints.indices){ println("$i: ${ints[i]}") }
编辑 (回应评论):
当然, forEachIndexed
也可以在多维数组上使用:
val twoDim: Array = ... twoDim.forEachIndexed { i, innerArr -> innerArr.forEachIndexed { j, val -> println("$i,$j -> $val") } }
- 错误:实体类必须使用@Entity进行注释
- 无法导入AndroidJUnit4和ActivityTestRule
- 预期types不接受Java中的空值,但Kotlin中的值可能为空
- 将android hashmap转换为kotlin
- Android Kotlin nextin排除了最后的随机食物
- 将Kotlin添加到现有Java项目会打破Android Studio gradle消息错误
- Android studio 3稳定版“房间1(RC)”的“app:kaptDebugKotlin”错误
- 在kotlin android tailrec函数返回0
- ResourceNotFoundException在升级到Canary 6后,在API 16 AVD上运行Kotlin项目