Kotiln控制流

Kotiln控制流

if 表達式

Kotlin沒有三元運算符(condition?then:else),因爲if語句已經滿足了效果。在Kotlin中,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){
print("Choose a")
a
}
else{
print("Choose b")
b
}

如果使用If作爲表達式而不是語句(例如,返回其值或將其賦值給一個變量),則需要有一個else分支。

When 表達式

when 取代了java風格語言的 switch 。最簡單的用法像下面這樣:

when (x) {
    1 -> print("x == 1")
    2 -> print("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 encode x")
    else -> print("s does not encode x")
}

甚至可以用 in 或者 !in 檢查值是否值在一個範圍或一個集合中:

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 casts ,你可以
不用另外的檢查就可以使用相應的屬性或方法。

val hasPrefix = when (x) {
    is String -> x.startsWith("prefix")
    else -> false
}

when 也可以用來代替 if-else if 。如果沒有任何參數提供,那麼分支的條件就是簡
單的布爾表達式,當條件爲真時執行相應的分支:

when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}

for 循環

for 循環通過任何提供的迭代器進行迭代。語法是下面這樣的:

for (item in collection)
    print(item)

內容可以是一個語句塊:

for (item: Int in ints){
    // ...
}

對數組的for循環不會創建迭代器對象,而是被編譯成一個基於索引的循環。如果你想通過 list 或者 array 的索引進行迭代,你可以這樣做:

for (i in array.indices)
    print(array[i])

在沒有其它對象創建的時候 “iteration through a range ” 會被自動編譯成最優的實
現。
或者,您可以使用 withIndex 庫函數

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

while 循環

while 和 do…while 像往常那樣

while (x > 0) {
    x--
}
do {
    val y = retrieveData()
} while (y != null) // y 在這是可見的

返回與跳轉

Kotlin 有三種結構跳轉表達式:

  • return
  • break 結束最近的閉合循環
  • continue 跳到最近的閉合循環的下一次循環

break 和 continue 標籤
在 Kotlin 中表達式可以添加標籤。標籤通過 @ 結尾來表示,比
如: abc@ , fooBar@ 都是有效的(參看語法)。使用標籤語法只需像這樣:

loop@ for (i in 1..100){
// ...
}

現在我們可以用標籤實現 break 或者 continue 的快速跳轉:

loop@ for (i in 1..100) {
    for (j in i..100) {
        if (...)
        break@loop
    }
}

break 是跳轉標籤後面的表達式,continue 是跳轉到循環的下一次迭代。

return標籤

return允許我們返回到外層函數

最重要的例子就是從字面函數中返回:

fun foo() {
    ints.forEach {
    if (it == 0) return
        print(it)
    }
}

return 表達式返回到最近的閉合函數,比如foo(注意這樣非局部返回僅僅可以在內聯函數中使用)。如果我們需要從一個字面函數返回可以使用標籤修飾 return :

fun foo() {
    ints.forEach lit@ {
    if (it ==0) return@lit
        print(it)
    }
}

現在它僅僅從字面函數中返回。經常用一種更方便的含蓄的標籤:比如用和傳入的lambda表達式名字相同的標籤。

fun foo() {
    ints.forEach {
    if (it == 0) return@forEach
        print(it)
    }
}

另外,我們可以用函數表達式替代匿名函數。在函數表達式中使用 return 語句可以從函數表達式中返回。

fun foo() {
    ints.forEach(fun(value: Int){
    if (value == 0) return
        print(value)
    })
}

當返回一個值時,解析器給了一個參考,比如:

return@a 1

表示 “在標籤 @a 返回 1 ” 而不是返回一個標籤表達式 (@a 1)
命名函數自動定義標籤:

foo outer() {
    foo inner() {
        return@outer
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章