Kotlin 代码实践:循环与迭代

本部分介绍 Kotlin 中循环和迭代的实践应用。

可迭代条件标记

在 Kotlin 中,do-while 循环的条件标记可以在循环体内声明:

do {
    var cont = true 
    if (Random.nextBoolean()) {
        cont = false 
    }
} while (cont)

通过索引迭代

在 Kotlin 中,可以使用 withIndex() 函数通过索引迭代集合:

val xs: List = listOf('a', 'b', 'c')

// 使用 withIndex() 函数
for ((i, x) in xs.withIndex()) {
    println("$i $x") 
}

// 使用 forEachIndexed() 函数
xs.forEachIndexed { i, x -> 
    println("$i $x") 
}

以上代码展示了两种通过索引迭代 List 的方式:

  1. 使用 withIndex() 函数获取索引-元素对,并使用 for 循环遍历。
  2. 使用 forEachIndexed() 函数直接迭代索引和元素。
zip 文件大小:96.17KB