when 语句是 Java中 switch 的强化版,它对一个值进行判断,直到匹配到或者没有可匹配的值。
有参数 when
when单值匹配
当 when 语句没有返回值时,就不必要列举出所有的可能性,如:
fun whenFun(x: Int) {
when(x) {
0 -> "less than 2"
1 -> "less than 2"
}
}
上面的 whenFun函数并没有声明返回值,所以只列举了0和1这两种情况IDE也没有报错。但是如果声明了返回值,那就必须要列举出所有的可能性,以便能处理所以的情况。下面是有返回值的情况:
fun whenFun(x: Int): String {
return when(x) {
0 -> "less than 2"
1 -> "less than 2"
else -> "others"
}
}
// 或者以下写法
fun whenFun(x: Int): String {
val result = when(x) {
0 -> "less than 2"
1 -> "less than 2"
else -> "others"
}
return result
}
声明了返回值必须要列出所有情况,上面函数其他情况用 else 处理了。
when分支合并
when分支还可以合并,例如上面的例子?可以写成
fun whenFun(x: Int): String {
return when(x) {
0, 1 -> "less than 2"
else -> "others"
}
}
匹配函数
when语句的分支不仅仅是单个值,还可以是一个函数。下列函数输入一个x,判断函数Math.abs(x)的返回值是否和x相等。
fun getAbs(x: Int) = {
when (x) {
Math.abs(x) -> true
else -> false
}
}
>> println(getAbs(-5))
() -> kotlin.Boolean // 直接用 = 号返回的是返回值的类型
fun getAbs(x: Int): Boolean {
return when (x) {
Math.abs(x) -> true
else -> false
}
}
>> println(getAbs(-5))
false // 有具体返回值类型则返回的是具体的类型
匹配区间
fun isInRange(x: Char): Boolean {
return when (x) {
in 'a'..'z' -> true
else -> false
}
}
>> println(isInRange('g'))
true
使用了 in 关键字,判断字符x是否在字符区间内,区间也可用数字区间,数组、集合等。
// 数字区间
fun isInRange(x: Int): Boolean {
return when (x) {
in 1..10 -> true
else -> false
}
}
>> println(isInRange(20))
false
// 集合区间
fun isInRange(x: Int): Boolean {
return when (x) {
in listOf(1, 2, 3, 4, 5) -> true
else -> false
}
}
>> println(isInRange(4))
true
// 数组区间
fun isInRange(x: Int): Boolean {
return when (x) {
in arrayOf(1, 2, 3, 4, 5) -> true
else -> false
}
}
>> println(isInRange(4))
true
类型匹配
判断输入的类型是否是某类型
fun isString(x: Any): Boolean {
return when (x) {
is String -> true
else -> false
}
}
>> println(isString("Kotlin"))
true
无参数when
无参数when类似多分支的 if-else。
fun compareInt(x: Int, y: Int): String {
return when {
x > y -> "$x is more than $y"
else -> "$x is less than $y"
}
}
>> println(compareInt(5, 10))
5 is less than 10
注意:无参数when,when关键字后面不带括号,分支中的 -> 左右都是一个表达式,左边表达式为 Boolean类型,表达式的结果为true时才会触发 -> 右边的结果