20200204[轉]Kotlin-When表達式

0 原文

1. When表達式

when 將它的參數和所有的分支條件順序比較,直到某個分支滿足條件。

when 既可以被當做表達式使用也可以被當做語句使用。如果它被當做表達式,符合條件的分支的值就是整個表達式的值,如果當做語句使用, 則忽略個別分支的值。

when 類似其他語言的 switch 操作符。其最簡單的形式如下:

fun main(args : Array<String>) {
    for (i in 1..10) {
        println(getType(i))
    }
}

fun getType(x: Int) :String {
    var result : String

    // 類似 Java 的Switch
    when(x) {
        1 -> result = "type 1"
        2 -> result = "type 2"
        3 -> result = "type 3"
        4 -> result = "type 4"
        5, 6 -> result = "type 5, 6"
        in 7..8 -> result = "type 7, 8"
        // 類似 Java 的 Default
        else -> result = ("unknow type, vaule" + x)
    }

    return result
}

運行結果如下:

type 1
type 2
type 3
type 4
type 5, 6
type 5, 6
type 7, 8
type 7, 8
unknow type, vaule9
unknow type, vaule10

Process finished with exit code 0

2 使用 is 智能轉換

另一種可能性是檢測一個值是(is)或者不是(!is)一個特定類型的值。注意: 由於智能轉換,你可以訪問該類型的方法和屬性而無需 任何額外的檢測。

fun main(args : Array<String>) {
    isNumber(123)

    isNumber("hello world")

    isNumber(true)
}

fun isNumber(x : Any) = when (x){
    is Int -> println("is number:" + x)
    is String -> println("is not number, is String :" + x)
    else -> println("is not number, is unknow :" + x)
}

運行結果

is number:123
is not number, is String :hello world
is not number, is unknow :true

Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章