Kotlin 循環(huán)控制
循環(huán)控制語(yǔ)句也是每門(mén)語(yǔ)言不可缺少的一部分,一般就是我們所熟知的 for
、while
、do-while
。Kotlin 循環(huán)其實(shí)幾乎和 Java中 的一模一樣。
1. for 循環(huán)
for 循環(huán) 可以對(duì)任何提供迭代器(iterator)的對(duì)象進(jìn)行遍歷,for 循環(huán)僅以唯一一種形式存在, 和 Java的 for-each 循環(huán)一致。其寫(xiě)法for <item> in <elements>
和 C# 一樣。和 Java 類(lèi)似,循環(huán)最常見(jiàn)的應(yīng)用就是迭代集合,具體語(yǔ)法如下:
for (item in list) println(item)
//循環(huán)體還可以是個(gè)代碼塊
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) {//類(lèi)似于java中的數(shù)組的length-index的遍歷
println("The $index index is ${items[index]}")
}
2. while 和 do-while 循環(huán)
Kotlin 中 while
和do-while
循環(huán),它們的語(yǔ)法和 Java 中相應(yīng)的循環(huán)沒(méi)什么區(qū)別:
//當(dāng)condition為true時(shí)執(zhí)行循環(huán)體
while(condition) {
/*...*/
}
//循環(huán)體第一次會(huì)無(wú)條件地執(zhí)行。此后,當(dāng)condition為true時(shí)才執(zhí)行
do {
/*...*/
} while (condition)
val items = listOf("java", "kotlin", "android")
var index = 0
while (index < items.size) {//while 循環(huán)的遍歷方式
println("The $index lang is ${items[index++]}")
}
3. 迭代區(qū)間和數(shù)列
如上所述,for 可以循環(huán)遍歷任何提供了迭代器的對(duì)象。即:有一個(gè)成員函數(shù)或者擴(kuò)展函數(shù) iterator()
,它的返回類(lèi)型,有一個(gè)成員函數(shù)或者擴(kuò)展函數(shù) next()
,并且有一個(gè)成員函數(shù)或者擴(kuò)展函數(shù) hasNext()
返回 Boolean
。
如需在數(shù)字區(qū)間上迭代,請(qǐng)使用區(qū)間表達(dá)式:
for (i in 1..10) {//遍歷區(qū)間,注意Kotlin的區(qū)間的包含或是閉合的。
print("$i ")
}
//輸出結(jié)果: 1 2 3 4 5 6 7 8 9 10
for (i in 1 until 10) {
print("$i ")
}
//輸出結(jié)果: 1 2 3 4 5 6 7 8 9
for (i in 10 downTo 1 step 2) {
print("$i ")
}
//輸出結(jié)果: 10 8 6 4 2
對(duì)區(qū)間或者數(shù)組的 for
循環(huán)會(huì)被編譯為并不創(chuàng)建迭代器的基于索引的循環(huán)。
如果想要通過(guò)索引遍歷一個(gè)數(shù)組或者一個(gè) list,可以這么做:
for (i in array.indices) {//遍歷索引
println(array[i])
}
或者可以用庫(kù)函數(shù) withIndex
:
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
4. 迭代 map
在 Kotlin 使用 for...in
循環(huán)的最常見(jiàn)的場(chǎng)景迭代集合, 可以使用 for-in
來(lái)迭代 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. 循環(huán)中的 break 與 continue
在循環(huán)中 Kotlin 支類(lèi)似 Java 中 break
和 continue
操作符。
- break:終止最直接包圍它的循環(huán);
- continue:繼續(xù)下一次最直接包圍它的循環(huán)。
for (i in 1..100) {
if (i % 2 == 0) continue // 如果 i 能整除于 2,跳出本次循環(huán),否則進(jìn)入下層循環(huán)
for (j in 1..100) {
if (j < 50) break // 如果 j 小于 50 ,終止循環(huán)。
}
}
6. 小結(jié)
到這里有關(guān) Kotlin 中的循環(huán)控制就結(jié)束了,基礎(chǔ)語(yǔ)法篇也就結(jié)束了,下一篇我們將進(jìn)入 Kotlin 中的高級(jí)語(yǔ)法篇。