kotlin基础<四>
‘when’ expression
kotlin中的when和Java中的switch有着相似的的功能,但when比switch强大太多太多。
你可以用when来处理枚举类:
enum class Size(val abbreviation: String) {
SMALL("S"), MEDIUM("M"),
LARGE("L"), EXTRA_LARGE("XL");
}
fun getResult(size: Size) =
when(size) {
Size.SMALL -> "no, that's too small~"
Size.EXTRA_LARGE -> "no, it doesn't fit me."
Size.LARGE -> "no, it's still too big~"
Size.MEDIUM -> "oh, this skirt looks good on me. "
}
fun main(vararg args:String) {
println(getResult(Size.MEDIUM))
}
//result:
//oh, this skirt looks good on me. when是个具有返回值的表达式,而且不像类C语言的switch那样写break。
when的语法如下(引用了官方文档说明):
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // 注意这个块
print("x is neither 1 nor 2")
}
}
when将它的参数和所有的分支条件顺序比较,直到某个分支满足条件。when既可以被当做表达式使用也可以被当做语句使用。如果它被当做表达式,符合条件的分支的值就是整个表达式的值,如果当做语句使用,则忽略个别分支的值。(像if一样,每一个分支可以是 一个代码块,它的值是块中最后的表达式的值。)如果其他分支都不满足条件将会求值else分支。如果when作为一个表达式使用,则必须有else分支,除非编译器能够检测出所有的可能情况都已经覆盖了。如果很多分支需要用相同的方式处理,则可以把多个分支条件放在一起,用逗号分隔:
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
} 我们可以用任意表达式(而不只是常量)作为分支条件:
when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
} 我们也可以检测一个值在( in )或者不在( !in )一个区间或者集合中:
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
} 另一种可能性是检测一个值是
(is)或者不是(!is)一个特定类型的值。注意:由于智能转换,你可以访问该类型的方法和属性而无需任何额外的检测。
val hasPrefix = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
when也可以用来取代if-else-if链。如果不提供参数,所有的分支条件都是简单的布尔表达式,而当一个分支的条件为真时则执行该分支:
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
京公网安备 11010502036488号