when 語句引數匹配

當給出一個引數時,when 語句將順序匹配分支的引數。使用 == 運算子完成匹配,該運算子執行空檢查並使用 equals 函式比較運算元。第一個匹配的將被執行。

when (x) {
    "English" -> print("How are you?")
    "German" -> print("Wie geht es dir?")
    else -> print("I don't know that language yet :(")
}

when 語句還知道一些更高階的匹配選項:

val names = listOf("John", "Sarah", "Tim", "Maggie")
when (x) {
    in names -> print("I know that name!")
    !in 1..10 -> print("Argument was not in the range from 1 to 10")
    is String -> print(x.length) // Due to smart casting, you can use String-functions here
}