Kotlin中的when表达式对标Java中的Switch Case,同时它的功能更为强大,更为灵活和更具表现力
1.基本的 when 表达式语法
注意when表达式中,没有break或continue,同时使用 -> 箭头函数指向代码块
fun main(args: Array<String>) {
val x = 2
when (x) {
1 -> println("Value of x is 1")
2 -> println("Value of x is 2")
}
}
输出:
Value of x is 2
2. when 表达式的默认分支
当我们的需要的分支枚举完毕,可以使用 else 指向默认分支
fun main(args: Array<String>) {
val x = 100
when (x) {
1 -> println("Value of x is 1")
2 -> println("Value of x is 2")
else -> print("Value of x is $x")
}
}
输出:
Value of x is 100
3. when 表达式中使用范围表达式
fun main(args: Array<String>) {
val x = 15
val numbersList = arrayListOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
when (x) {
in 1..10 -> println("x is in range of 1 to 10")
in numbersList -> print("x in numbersList range")
else -> print("X is not in the range and its value of x is $x")
}
}
输出:
x in numbersList range
或者范围表达式取非
fun main(args: Array<String>) {
val x = 15
when (x) {
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
}
输出:
none of the above
4. when 表达式嵌套语句示例
如符合条件就打印输出,同时返回数值
fun main(args: Array<String>) {
val x = 10
val y = 7
val z = 20
val result = when (z) {
20 -> {
println("if z id 20 then doing the sum of x and y")
x + y
}
30 -> {
println("if z id 30 then subtracting y from x")
x - y
}
else -> "none of the value matched"
}
println("The result is $result")
}
输出:
if z id 20 then doing the sum of x and y
The result is 17
5. when 表达式还可以判断字符串
fun main(args: Array<String>) {
val namesList= listOf("Waheed","Ali","Akhtar")
val name="Waheed"
when (name) {
in namesList-> print("User $name exists in our database")
else -> "name $name does not exit"
}
}
输出:
User Waheed exists in our database