kotlin中when的默认分支
时间: 2024-04-02 10:10:41 浏览: 16
kotlin中的when语句必须包含一个else分支,否则会产生编译错误。当所有的分支都不匹配时,else分支会被执行。如果你不需要执行任何操作,你可以将else分支留空,或者使用一个Unit表达式,如下所示:
```
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
else -> Unit
}
```
相关问题
kotlin中when的用法
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")
}
```
kotlin中使用when
在Kotlin中,when是一个强大的控制结构,类似于Java中的switch语句。when表达式可以用于任何类型的值,不仅限于整数和枚举类型。以下是使用when表达式的基本语法:
```kotlin
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
```
在这个例子中,当x等于1时,输出“x == 1”,当x等于2时,输出“x == 2”,否则输出“x is neither 1 nor 2”。
when表达式也可以用于检查一个对象是否属于某个类型:
```kotlin
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
```
在这个例子中,当obj是1时,返回“One”,当obj是字符串“Hello”时,返回“Greeting”,当obj是Long类型时,返回“Long”,当obj不是字符串类型时,返回“Not a string”,否则返回“Unknown”。