Kotlin 控制流

if 表達式

在 kotlin 中,if 是一個表達式,即他會返回一個值,因此就不需要三元運算符(條件? 然後:否則) .

fun getMax(): Int {
    var a: Int = 1
    var b: Int = 2
    return if (a > b) a else b
}

if 的分支可以是代碼塊,最後的表達式作爲該塊的值

fun getMaxCode(a: Int, b: Int): Int {
    val max = if (a > b) {
        println("A is max")
        11     // 作爲返回值
    } else {
        println("B is max")
        22     // 作爲返回值
    }
    return max     // 最後的返回值 max 取值爲 11 或 22
}

when 表達式

when 取代了 Java 中的 switch 關鍵字, when 將他的參數與所有的分支條件順序比較,直到 某個分支滿足條件,滿足條件的分支後,會自動終止 when 語句的執行,因此,並不需要像 switch 語句的第一個滿足條件的分支的後面添加 break.

fun testWhen(x: Int) {
    when (x) {
        1 -> {      // 如果分支中是多條語句,則需要使用 {} 
            println("x = 1")
            println("1111111")
        }
        2 -> println("x = 2")
        else -> {
            println("x is neither 1 or 2")
        }
    }
}

如果很多分支需要用相同的方式處理,則可以把多個分支條件放在一起,用 逗號 分割。

fun testWhen1(x:Int) {
    when (x) {
        1,2 -> println("the x is 1 or 2")
        else -> {
            println("x is neither 1 or 2")
        }
    }
}

也可以檢測一個值在 (in) 或不在 (!in) 一個區間或集合中

fun testWhen3(num: Int) {
    when (num) {
        in 1..10 -> println("num is in 1..10")
        !in 10..20 -> println("num is outside the range")
        else -> println("none of above")
    }
}

for 循環

for 循環可以對任何提供迭代器的對象進行遍歷,這相當於 java 中的 foreach 循環。

fun testFor1() {
    // 聲明一個數組
    var itemsArray = arrayOf(1, 2, 3, 4, 5)
    // 聲明一個 list
    var itemsList = listOf<String>("apple", "orange")
    for (item: Int in itemsArray) {
        println("the array data : $item")
    }
    for(index in itemsArray.indices) {
        println("the index $index data is  ${itemsArray[index]}")
    }

    for (item: String in itemsList) {
        println("the array data : $item")
    }
}

While 循環

while 與 do… while 和 Java 中的用法是一樣的。

fun testWhile(x: Int) {
    var num = x
    while (num > 0) {
        num--
        println("num  = $num ")
    }
}
fun testDoWhile() {
    var num: Int = 10;
    do {
        num--
        println("num is $num")
    } while (num > 0)
}

返回和跳轉

kotlin 中有三種結構化跳轉表達式

  • return : 默認從最直接包圍他的函數或匿名函數返回‘
  • break : 終止最直接包圍他的循環。
  • continue : 繼續下一次最直接包圍他的循環。

在 kotlin 中任何表達式都可以用標籤 label 來標記,標籤的格式爲標識符後跟 @ 符號,

fun testLabel() {
    loop@ for (i in 1..10) {     // 使用 loop@ 標記外層循環
        for (j in 1..i) {
            if (i == 9) {
                break@loop       // 跳出外層循環       
            }
            print("$j * $i = ${i * j}   ")

        }
        println()
    }
}

標籤處返回

kotlin 有函數字面量,局部函數和對象表達式,因此 kotlin 的函數可以被嵌套

fun testReturn() {
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return
        print("$it ,")
    }
}
// 1 ,2 ,

// 這個 return 表達式從最直接包圍他的函數 testReturn 中返回,如果我們需要從 lambda 表達式中返回,我們必須給他加標籤並用 “限制return” 
fun testReturn1() {
    listOf(1, 2, 3, 4, 5).forEach  lit@{
        if (it == 3) return@lit
        print("$it ,")
    }
}
// 1 ,2 ,4 ,5 ,
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章