kotlin when
时间: 2023-07-26 08:24:07 浏览: 50
Kotlin中的when语句类似于Java中的switch语句,但提供了更多的功能和灵活性。when语句可以用于任何数据类型,包括枚举和任何类的实例。下面是一个简单的Kotlin when语句示例:
```
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
3, 4 -> println("x is 3 or 4")
in 5..10 -> println("x is between 5 and 10")
else -> println("x is not in the range")
}
```
在这个例子中,我们对变量x进行了匹配,然后根据不同的情况进行了不同的操作。如果x等于1,我们打印“x is 1”,如果x等于2,我们打印“x is 2”,以此类推。当然,我们也可以使用范围、多个值和其他表达式来匹配x的值。最后,如果没有匹配到任何情况,我们打印“x is not in the range”。
相关问题
kotlin when 用法
Kotlin中的when表达式是一种强大的条件控制结构,类似于其他编程语言中的switch语句。它可以根据不同的条件执行不同的代码块。下面是Kotlin中when表达式的用法:
1. 基本用法:
当需要根据一个变量的值来执行不同的代码块时,可以使用when表达式。例如:
```kotlin
val x = 5
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
else -> println("x is neither 1 nor 2")
}
```
当x的值为1时,输出"x is 1";当x的值为2时,输出"x is 2";否则输出"x is neither 1 nor 2"。
2. 多个条件匹配:
可以在一个when表达式中匹配多个条件。例如:
```kotlin
val y = 3
when (y) {
1, 2 -> println("y is either 1 or 2")
in 3..5 -> println("y is between 3 and 5")
else -> println("y is neither 1 nor 2, nor between 3 and 5")
}
```
当y的值为1或2时,输出"y is either 1 or 2";当y的值在3到5之间时,输出"y is between 3 and 5";否则输出"y is neither 1 nor 2, nor between 3 and 5"。
3. 使用表达式作为条件:
当需要根据表达式的结果来执行不同的代码块时,可以将表达式作为when的条件。例如:
```kotlin
val z = 7
when {
z < 0 -> println("z is negative")
z > 0 -> println("z is positive")
else -> println("z is zero")
}
```
当z小于0时,输出"z is negative";当z大于0时,输出"z is positive";否则输出"z is zero"。
以上是Kotlin中when表达式的基本用法和常见用法。如果还有其他问题,请继续提问。
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”。