亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

Kotlin 循環控制

循環控制語句也是每門語言不可缺少的一部分,一般就是我們所熟知的 for、whiledo-while。Kotlin 循環其實幾乎和 Java中 的一模一樣。

1. for 循環

for 循環 可以對任何提供迭代器(iterator)的對象進行遍歷,for 循環僅以唯一一種形式存在, 和 Java的 for-each 循環一致。其寫法for <item> in <elements>和 C# 一樣。和 Java 類似,循環最常見的應用就是迭代集合,具體語法如下:

for (item in list) println(item)

//循環體還可以是個代碼塊
for (item in list) {
    //...
}


val items = listOf("java", "kotlin", "android")

//for-in遍歷
for (item in items) {//for遍歷集合
    println("lang $item")
}

//遍歷索引
for (index in items.indices) {//類似于java中的數組的length-index的遍歷
    println("The $index index is ${items[index]}")
}

2. while 和 do-while 循環

Kotlin 中 whiledo-while 循環,它們的語法和 Java 中相應的循環沒什么區別:

//當condition為true時執行循環體
while(condition) {
    /*...*/
}

//循環體第一次會無條件地執行。此后,當condition為true時才執行
do {
    /*...*/
} while (condition)


val items = listOf("java", "kotlin", "android")
var index = 0
while (index < items.size) {//while 循環的遍歷方式
    println("The $index lang is ${items[index++]}")
}

3. 迭代區間和數列

如上所述,for 可以循環遍歷任何提供了迭代器的對象。即:有一個成員函數或者擴展函數 iterator(),它的返回類型,有一個成員函數或者擴展函數 next(),并且有一個成員函數或者擴展函數 hasNext() 返回 Boolean

如需在數字區間上迭代,請使用區間表達式

for (i in 1..10) {//遍歷區間,注意Kotlin的區間的包含或是閉合的。
    print("$i ")
}
//輸出結果: 1 2 3 4 5 6 7 8 9 10 

for (i in 1 until 10) {
    print("$i ")
}
//輸出結果: 1 2 3 4 5 6 7 8 9

for (i in 10 downTo 1 step 2) {
    print("$i ")
}
//輸出結果: 10 8 6 4 2

對區間或者數組的 for 循環會被編譯為并不創建迭代器的基于索引的循環。

如果想要通過索引遍歷一個數組或者一個 list,可以這么做:

for (i in array.indices) {//遍歷索引
    println(array[i])
}

或者可以用庫函數 withIndex

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

4. 迭代 map

在 Kotlin 使用 for...in 循環的最常見的場景迭代集合, 可以使用 for-in 來迭代 map

val binaryReps = mutableMapOf<Char, String>()
for(char in 'A'..'F') {
    val binary = Integer.toBinaryString(char.toInt())
    binaryReps[char] = binary 
}

for((letter, binary) in binaryReps) { //for-in 遍歷map
    println("$letter = $binary")
}

5. 循環中的 break 與 continue

在循環中 Kotlin 支類似 Java 中 breakcontinue 操作符。

  • break:終止最直接包圍它的循環;
  • continue:繼續下一次最直接包圍它的循環。
for (i in 1..100) {
    if (i % 2 == 0) continue // 如果 i 能整除于 2,跳出本次循環,否則進入下層循環
    for (j in 1..100) { 
        if (j < 50) break // 如果 j 小于 50 ,終止循環。
    }
}

6. 小結

到這里有關 Kotlin 中的循環控制就結束了,基礎語法篇也就結束了,下一篇我們將進入 Kotlin 中的高級語法篇。

圖片描述