歡迎關注 二師兄Kotlin
轉(zhuǎn)載請注明出處 二師兄kotlin
流程控制
If表達式
在Kotlin中,if是表達式,它可以有返回值。所以三元表達式(? :)就沒有存在的必要了,if替代了它的角色。
// 傳統(tǒng)用法
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) {
print("Choose a")
a
}
else {
print("Choose b")
b
}
如果把if當作表達式使用(例如把它的返回值賦給一個變量),else分支是必須的。
詳情請查看if語法。
When表達式
when替代了類C語言中的switch操作符,一個最簡單寫法如下:
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
when按順序把參數(shù)和每一個分支匹配直達找到滿足條件的分支。when既可以用作表達式又可以用作分支語句。如果被用作表達式,匹配的分支就是整個表達式的返回值。如果用作分支語句,每個分支的執(zhí)行結(jié)果將被忽略。(和if一樣,每個分支也可以是語句塊,最后一條語句的執(zhí)行結(jié)果就是語句塊的返回值)
如果沒有匹配的分支,else分支會默認執(zhí)行。如果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 encode x")
}
也可以用in
或者!in
來檢查一個值是否在一個rang
或一個集合內(nèi):
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
也可以用is
或者!is
判斷一個值是不是屬于某個的類型。這里要注意,由于有smart cast,你不需要額外檢查就可以直接訪問這個類型的屬性和方法。
val hasPrefix = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
when也可以代替if-else-if
鏈。如果沒有提供參數(shù),分支條件就僅僅是布爾表達式,對應分支也只會在true的情況下才被執(zhí)行:
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
詳情請看when的語法
For循環(huán)
for循環(huán)可以遍歷任何提供了迭代器的東西。語法如下:
for (item in collection)
print(item)
循環(huán)體也可以是語句塊:
for (item: Int in ints) {
// ...
}
上文提到的,for可以遍歷任何提供了迭代器的東西,例如:
有一個成員或者擴展函數(shù)iterator()
,它的返回類型
- 包含一個成員或擴展函數(shù)
next()
,且 - 包含一個成員或者擴展函數(shù)
hasNext()
,它的返回值是Boolean
以上三個函數(shù)都必須被標記為操作符(operator)
。
for循環(huán)用在數(shù)組上會被編譯為一個基于索引的循環(huán),并不會創(chuàng)建一個迭代器。
如果你想通過索引遍歷數(shù)組或list,你可以這么做:
for (i in array.indices)
print(array[i])
請注意,類似這樣對range的遍歷會被編譯器優(yōu)化,不會創(chuàng)建任何額外的對象。
另外,你可以使用庫函數(shù)withIndex
:
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
詳情請看for語法。
While循環(huán)
while和do...while跟其他語言沒什么兩樣:
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // 此處y是可見的!
詳情請看while語法。
Break和Continue
Kotlin支持在循環(huán)中使用傳統(tǒng)意義上的Break和Continue。詳情查看Returns and jumps。
與Java相比,Kotlin流程控制簡單總結(jié)為:
1. while還是那個while
2. when取代了switch
3. if兼職了表達式