Kotlin學習之-4.3.3 控制流
if 表達式
Kotlin中,if
是一個表達式,他會返回一個值。 因此沒有三元操作符(condition ? then : else
), if
表達式可以很好的表達這樣的功能。
// 普通用法
var max = a
if (a < b) max = b
// 帶else 的表達式
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// 表達式寫法
val max = if (a > b) a else b
if
的條件分支可以是塊語句,最後一行語句是該塊語句的值, 例如:
val max = if (a > b) {
println("Choose a")
a
} else {
println("Choose b")
b
}
如果用一個if
表達式形式,而不是一個語句形式(例如,返回一個值或者賦給另外一個變量), 那麼這個表達式就必須要有else
分支
when 表達式
when
替換了C 語言中類似的switch
操作符。 簡單的寫法如下:
when(x) {
1 -> println("x == 1")
2 -> pringln("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
when
順序地用它的參數來匹配所有的分支條件,直到有一個條件滿足。 when
既可以被寫成表達式形式,也可以寫成語句形式。 如果用表達式形式,滿足條件的分支的返回值就是整個表達式的返回值;如果用語句形式,每個條件分支的值被忽略。(就像if
, 每個分支可以是一個塊語句,並且它的值是它最後一條語句的值)
else
分支在其他分支都沒有滿足的時候,會被檢查。如果when
使用表達式形式,那麼else
分支是強制要求的,除非編譯器能夠證明所有可能的情況在分之中都被覆蓋了。
如果多種情況的處理情況是一樣的,那麼分支條件可以用逗號組合起來:
when (x) {
0, 1 -> print("x == 0 or x ==1")
else -> print("otherwise")
}
也可以使用完整的表達式當做分支的條件語句:
when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encdoe x")
}
還可以使用範圍表達式range
當做分支條件來撿來是否處在一個範圍
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> pint("x is outside the range")
else -> print("none of the above")
}
分支條件還可以檢查是否是某個類型。由於自動轉換類型的原因,在分支中,可以直接使用該類型的方法和屬性,而不需要再檢查類型:
fun hasPrefix(x: Any) = when (x) {
is String -> x.startWith("prefix")
else -> false
}
when
語句還可以當做多重if-else
語句的替換。如果when
語句沒有參數,分支條件就是簡單的布爾表達式,分支語句會在條件爲真的時候執行。
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
## for 循環語句
`for` 循環可以遍歷任何有迭代器的對象。語法如下:
```kotlin
for (item in collection) print(item)
<div class="se-preview-section-delimiter"></div>
主題可以是塊語句
for (item in collection) {
// ...
}
<div class="se-preview-section-delimiter"></div>
如上所述,for
循環可以遍歷任何有迭代器的對象。例如
- 有一個迭代器的成員函數或者擴展函數
iterator()
,它的返回值
- 有一個成員函數或者擴展函數
next()
並且 - 有一個成員函數或者擴展函數
hasNext()
,返回值是Boolean
- 有一個成員函數或者擴展函數
所有這些函數都應該是被標記爲operator
一個for
循環遍歷一個數組會被編譯成基於座標的循環,而不會創建一個迭代器對象。
如果想要通過座標來遍歷一個數組或者列表,可以這樣做:
for (i in array.indices) {
print(array[i])
}
<div class="se-preview-section-delimiter"></div>
注意通過範圍來遍歷會被編譯後優化,不會生成新的對象
另外,還可以使用withIndex
庫函數來訪問數組或者列表:
for ((index, value) in array.withIndex()) {
println(" the element at $index is $value")
}
<div class="se-preview-section-delimiter"></div>
while 循環
while
和 do...while
都支持:
while (x > 0) {
x--
]
do {
val y = retrieveData()
} while (y != null) // y is visible here!
循環語句的中止
Kotlin 支持在循環語句中的break
和continue
操作。