kotlin中when的用法
时间: 2023-06-12 15:08:16 浏览: 353
Kotlin中的when语句类似于Java中的switch语句,但提供了更多功能和更强大的表达能力。下面是Kotlin中when语句的用法:
1. 基本用法:
```
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
else -> println("x is neither 1 nor 2")
}
```
2. 多个分支合并:
```
when (x) {
1, 2 -> println("x is either 1 or 2")
else -> println("x is neither 1 nor 2")
}
```
3. 使用in运算符:
```
when (x) {
in 1..10 -> println("x is between 1 and 10")
!in 10..20 -> println("x is not between 10 and 20")
else -> println("x is not in any range")
}
```
4. 使用is运算符:
```
when (x) {
is String -> println("x is a String")
is Int -> println("x is an Int")
else -> println("x is neither a String nor an Int")
}
```
5. 使用表达式作为分支:
```
when {
x % 2 == 0 -> println("x is even")
x % 2 != 0 -> println("x is odd")
else -> println("x is not a number")
}
```
6. 在when语句中使用lambda表达式:
```
when (x) {
in 1..10 -> {
println("x is between 1 and 10")
println("x + 1 is ${x + 1}")
}
else -> println("x is not between 1 and 10")
}
```
阅读全文