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
}