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") } }
- Android Anko警报与自定义视图错误(Kotlin)
- NullPointerException在Kotlin中
- 各种问题@NonNull,@NotNull和@ParametersAreNonnullByDefault
- Kotlin属性与getter。 我可以不指定初始值吗?
- 使用RxAndroid处理onKeyDown
- 以编程方式更改可绘制的颜色
- 房间编译器java.lang.NoClassDefFoundError:org / jetbrains / annotations / NotNull
- Varargs Kotlin Java互操作不正常
- 未解决的参考DaggerApplicationComponent