0 原文
1. When表达式
when 将它的参数和所有的分支条件顺序比较,直到某个分支满足条件。
when 既可以被当做表达式使用也可以被当做语句使用。如果它被当做表达式,符合条件的分支的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值。
when 类似其他语言的 switch 操作符。其最简单的形式如下:
fun main(args : Array<String>) {
for (i in 1..10) {
println(getType(i))
}
}
fun getType(x: Int) :String {
var result : String
// 类似 Java 的Switch
when(x) {
1 -> result = "type 1"
2 -> result = "type 2"
3 -> result = "type 3"
4 -> result = "type 4"
5, 6 -> result = "type 5, 6"
in 7..8 -> result = "type 7, 8"
// 类似 Java 的 Default
else -> result = ("unknow type, vaule" + x)
}
return result
}
运行结果如下:
type 1
type 2
type 3
type 4
type 5, 6
type 5, 6
type 7, 8
type 7, 8
unknow type, vaule9
unknow type, vaule10
Process finished with exit code 0
2 使用 is 智能转换
另一种可能性是检测一个值是(is)或者不是(!is)一个特定类型的值。注意: 由于智能转换,你可以访问该类型的方法和属性而无需 任何额外的检测。
fun main(args : Array<String>) {
isNumber(123)
isNumber("hello world")
isNumber(true)
}
fun isNumber(x : Any) = when (x){
is Int -> println("is number:" + x)
is String -> println("is not number, is String :" + x)
else -> println("is not number, is unknow :" + x)
}
运行结果
is number:123
is not number, is String :hello world
is not number, is unknow :true
Process finished with exit code 0