12.md 3.6 KB
Newer Older
W
wizardforcel 已提交
1
# Kotlin `when`表达式
W
wizardforcel 已提交
2 3 4

> 原文: [https://www.programiz.com/kotlin-programming/when-expression](https://www.programiz.com/kotlin-programming/when-expression)

W
wizardforcel 已提交
5
#### 在本文中,您将借助各种示例来了解在 Kotlin 中的`when`结构。
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
## Kotlin `when`结构
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9
可以认为 Kotlin 中的`when`结构是 [Java `switch`语句](/java-programming/hello-world)的替代。 它求值许多替代方案中的一段代码。
W
wizardforcel 已提交
10 11 12

* * *

W
wizardforcel 已提交
13
### 示例:简单`when`表达式
W
wizardforcel 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

```kt
fun main(args: Array<String>) {

    val a = 12
    val b = 5

    println("Enter operator either +, -, * or /")
    val operator = readLine()

    val result = when (operator) {
        "+" -> a + b
        "-" -> a - b
        "*" -> a * b
        "/" -> a / b
        else -> "$operator operator is invalid operator."
    }

    println("result = $result")
}

```

当您运行程序时,输出将类似于:

```kt
Enter operator either +, -, * or /
*
result = 60
```

W
wizardforcel 已提交
45
上面的程序从用户那里获取输入字符串(建议阅读:[在 Kotlin 中获取用户的字符串输入](/kotlin-programming/input-output#input-string))。 假设用户输入了`*`。 在这种情况下,对表达式`a * b`求值,并将该值分配给变量`result`
W
wizardforcel 已提交
46

W
wizardforcel 已提交
47
如果不满足任何分支条件(用户输入`+``-``*``/`除外),则求值`else`分支。
W
wizardforcel 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

* * *

在上面的示例中,我们使用`when`作为表达式。 但是,使用`when`作为表达式不是强制性的。 例如,

```kt
fun main(args: Array<String>) {

    val a = 12
    val b = 5

    println("Enter operator either +, -, * or /")
    val operator = readLine()

    when (operator) {
        "+" -> println("$a + $b = ${a + b}")
        "-" -> println("$a - $b = ${a - b}")
        "*" -> println("$a * $b = ${a * b}")
        "/" -> println("$a / $b = ${a / b}")
        else -> println("$operator is invalid")
    }
}
```

When you run the program, the output will be something like:

```kt
Enter operator either +, -, * or /
-
12 - 5 = 7

```

此处,`when`不是表达式(`when`的返回值未分配给任何东西)。 在这种情况下,`else`分支不是必需的。

* * *

W
wizardforcel 已提交
85
## 很小的可能性
W
wizardforcel 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

**将两个或多个分支条件与逗号组合。** 例如,

```kt
fun main(args: Array<String>) {

    val n = -1

    when (n) {
        1, 2, 3 -> println("n is a positive integer less than 4.")
        0 -> println("n is zero")
        -1, -2 -> println("n is a negative integer greater than 3.")
    }
}
```

运行该程序时,输出为:

```kt
n is a negative integer greater than 3.
```

* * *

**检查范围内的值。** 例如,

```kt
fun main(args: Array<String>) {

    val a = 100

    when (a) {
        in 1..10 -> println("A positive number less than 11.")
        in 10..100 -> println("A positive number between 10 and 100 (inclusive)")
    }
}
```

When you run the program, the output will be:

```kt
A positive number between 10 and 100 (inclusive)
```

* * *

**检查值是否为特定类型。**

W
wizardforcel 已提交
134
要在运行时检查值是否为特定类型,我们可以使用[`is`和`!is`运算符](https://kotlinlang.org/docs/reference/typecasts.html)。 例如,
W
wizardforcel 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

```kt
when (x) {
    is Int -> print(x + 1)
    is String -> print(x.length + 1)
    is IntArray -> print(x.sum())
}

```

* * *

**使用表达式作为分支条件。** 例如,

```kt
fun main(args: Array<String>) {

    val a = 11
    val n = "11"

    when (n) {
        "cat" -> println("Cat? Really?")
        12.toString() -> println("Close but not close enough.")
        a.toString() -> println("Bingo! It's eleven.")
    }
}
```

When you run the program, the output will be:

```kt
Bingo! It's eleven.

```