Kotlin for 循环

And*_*rea 1 android kotlin

我正在尝试学习 kotlin 语言(尤其是 Android),但我发现学习各种类型的 for 循环有些困难,那么普通 for 循环、for every 循环和 for every 索引之间有什么区别以及如何使用它?

例如在这篇文章中: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)
            }
        }
Run Code Online (Sandbox Code Playgroud)

他使用每个索引来迭代正方形(即二维数组)中包含的所有变量,但我真的不明白它是如何工作的。感谢任何帮助我的人!

s1m*_*nw1 5

以下是一些替代方案:

  1. 使用forEachIndexed:

    myList.forEachIndexed { i, element ->
        println(i)
        println(element)
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 可以在-each中使用的withIndex类型扩展:Iterablefor

    val ints = arrayListOf(1, 2, 3, 4, 5)
    
    for ((i, e) in ints.withIndex()) {
        println("$i: $e")
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 然后还有一个indices关于等的扩展属性Collection,Array它接近于forC、Java 等中的常见属性:

    for(i in ints.indices){
         println("$i: ${ints[i]}")
    }
    
    Run Code Online (Sandbox Code Playgroud)

编辑(回复评论):

当然,forEachIndexed也可以用于多维数组:

val twoDim: Array<IntArray> = ...

twoDim.forEachIndexed { i, innerArr ->               
    innerArr.forEachIndexed { j, val ->                
        println("$i,$j -> $val")              
    }                                                 
}                                                     
Run Code Online (Sandbox Code Playgroud)