Kotlin流程控制

if , when , for , while

if 表達(dá)式

在 Kotlin 中,if 是帶有返回值的表達(dá)式。因此Kotlin沒有三元運(yùn)算符(condition ? then : else),因?yàn)?if 語句可以做到同樣的事。

// 傳統(tǒng)用法
var max = a
if (a < b) max = b
// 帶 else
var max: Int
if (a > b) {
    max = a
}
else{
    max = b
}
// 作為表達(dá)式
val max = if (a > b) a else b

When 表達(dá)式

when 取代了 C 風(fēng)格語言的 switch 。最簡單的用法像下面這樣

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}

注:如果把 when 做為表達(dá)式的話 else 分支是強(qiáng)制的
如果有分支可以用同樣的方式處理的話,分支條件可以連在一起

when (x) {
    0,1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

可以用任意表達(dá)式作為分支的條件

when (x) {
    parseInt(s) -> print("s encode x")
    else -> print("s does not encode x")
}

is in

in 或者 !in 檢查值是否值在一個(gè)范圍或一個(gè)集合中

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 來判斷值是否是某個(gè)類型。

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

for 循環(huán)

for 循環(huán)可以對所有提供迭代器的變量進(jìn)行迭代。等同于 C# 等語言中的 foreach。語法形式

 for (item in 1..10)
        println(item)

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

while 循環(huán)

while 和 do...while 和其它語言沒什么區(qū)別

while (x > 0) {
    x--
}

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

在循環(huán)中使用 break 和 continue

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容