kotlin中使用when时如果有两个条件需要执行同样的代码时怎么写
时间: 2024-03-27 18:38:48 浏览: 27
在 Kotlin 中,使用 `when` 表达式时,可以使用逗号 `,` 来分隔多个条件,让它们执行同样的代码。例如:
```kotlin
val x = 1
when (x) {
0, 1 -> println("x is 0 or 1")
2 -> println("x is 2")
else -> println("x is neither 0, 1 nor 2")
}
```
在上面的代码中,当 `x` 的值为 0 或 1 时,都会执行 `println("x is 0 or 1")` 这行代码。使用逗号 `,` 分隔多个条件时,它们之间是或的关系。
如果需要执行多行代码,可以使用大括号 `{}` 将多行代码括起来。例如:
```kotlin
val x = 1
when (x) {
0, 1 -> {
println("x is 0 or 1")
println("Another line of code")
}
2 -> println("x is 2")
else -> println("x is neither 0, 1 nor 2")
}
```
在上面的代码中,当 `x` 的值为 0 或 1 时,会依次执行两行代码。
相关问题
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”。
kotlin中使用when重复标签
在 Kotlin 中,可以使用 `when` 关键字来实现类似于 `switch` 语句的功能。如果需要在 `when` 表达式中使用重复标签,可以使用 `continue@标签名` 和 `break@标签名` 的方式来指定标签名。
例如:
```kotlin
loop@ for (i in 1..3) {
println("外层循环:$i")
when (i) {
1 -> {
println("内层循环1")
for (j in 1..3) {
if (j == 2) continue@loop
println("内层循环1:$j")
}
}
2 -> {
println("内层循环2")
for (j in 1..3) {
if (j == 2) break@loop
println("内层循环2:$j")
}
}
3 -> {
println("内层循环3")
}
}
}
```
在上面的代码中,我们在外层循环上使用了一个标签 `loop`,然后在内层循环中使用了 `continue@loop` 和 `break@loop` 的方式来指定标签名。这样就可以在 `when` 表达式中使用重复标签了。