when
分支和某些静态已知始终失败的表达式。
示例:
fun process(x: Int?) {
val isNull = x == null
if (!isNull) {
if (x != null) {} // 条件始终为 true
require(x!! < 0 && x > 10) // 条件始终为 false
} else {
println(x!!) // !! operator will always fail
}
}
fun process(v: Any) {
when(v) {
is CharSequence -> println(v as Int) // 转换将始终失败
is String -> println(v) // 分支无法到达
}
}
2021.3 最新变化