@@ -27,10 +27,12 @@ fun main() {
27
27
// You can also use `else if` in expressions:
28
28
val maxLimit = 1
29
29
val maxOrLimit = if (maxLimit > a) maxLimit else if (a > b) a else b
30
-
31
- // sampleEnd
30
+
32
31
println (" max is $max " )
32
+ // max is 3
33
33
println (" maxOrLimit is $maxOrLimit " )
34
+ // maxOrLimit is 3
35
+ // sampleEnd
34
36
}
35
37
```
36
38
{kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="if-else-if-kotlin"}
@@ -50,71 +52,152 @@ val max = if (a > b) {
50
52
If you're using ` if ` as an expression, for example, for returning its value or
51
53
assigning it to a variable, the ` else ` branch is mandatory.
52
54
53
- ## When expression
55
+ ## When expressions and statements
56
+
57
+ ` when ` is a conditional expression that runs code based on multiple possible values or conditions. It is
58
+ similar to the ` switch ` statement in Java, C, and similar languages. For example:
59
+
60
+ ``` kotlin
61
+ fun main () {
62
+ // sampleStart
63
+ val x = 2
64
+ when (x) {
65
+ 1 -> print (" x == 1" )
66
+ 2 -> print (" x == 2" )
67
+ else -> print (" x is neither 1 nor 2" )
68
+ }
69
+ // x == 2
70
+ // sampleEnd
71
+ }
72
+ ```
73
+ {kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="kotlin-conditions-when-statement"}
74
+
75
+ ` when ` matches its argument against all branches sequentially until some branch condition is satisfied.
76
+
77
+ You can use ` when ` in a few different ways. Firstly, you can use ` when ` either as an ** expression** or as a ** statement** .
78
+ As an expression, ` when ` returns a value for later use in your code. As a statement, ` when ` completes an action
79
+ without returning anything of further use:
80
+
81
+ <table >
82
+ <tr >
83
+ <td>Expression</td>
84
+ <td>Statement</td>
85
+ </tr >
86
+ <tr >
87
+ <td >
88
+
89
+ ``` kotlin
90
+ // Returns a string assigned to the
91
+ // text variable
92
+ val text = when (x) {
93
+ 1 -> " x == 1"
94
+ 2 -> " x == 2"
95
+ else -> " x is neither 1 nor 2"
96
+ }
97
+ ```
54
98
55
- ` when ` defines a conditional expression with multiple branches. It is similar to the ` switch ` statement in C-like languages.
56
- Its simple form looks like this.
99
+ </ td >
100
+ < td >
57
101
58
102
``` kotlin
103
+ // Returns nothing but triggers a
104
+ // print statement
59
105
when (x) {
60
106
1 -> print (" x == 1" )
61
107
2 -> print (" x == 2" )
62
- else -> {
63
- print (" x is neither 1 nor 2" )
64
- }
108
+ else -> print (" x is neither 1 nor 2" )
65
109
}
66
110
```
67
111
68
- ` when ` matches its argument against all branches sequentially until some branch condition is satisfied.
112
+ </td >
113
+ </tr >
114
+ </table >
69
115
70
- ` when ` can be used either as an expression or as a statement. If it is used as an expression, the value
71
- of the first matching branch becomes the value of the overall expression. If it is used as a statement, the values of
72
- individual branches are ignored. Just like with ` if ` , each branch can be a block, and its value
73
- is the value of the last expression in the block.
116
+ Secondly, you can use ` when ` with or without a subject. Whether you use a subject with ` when ` or not, your expression or
117
+ statement behaves the same. We recommend using ` when ` with a subject when possible, as it makes your code easier to read
118
+ and maintain by clearly showing what you're checking.
74
119
75
- The ` else ` branch is evaluated if none of the other branch conditions are satisfied.
120
+ <table >
121
+ <tr >
122
+ <td>With subject <code>x</code></td>
123
+ <td>Without subject</td>
124
+ </tr >
125
+ <tr >
126
+ <td >
76
127
77
- If ` when ` is used as an _ expression_ , the ` else ` branch is mandatory,
78
- unless the compiler can prove that all possible cases are covered with branch conditions,
79
- for example, with [ ` enum ` class] ( enum-classes.md ) entries and [ ` sealed ` class] ( sealed-classes.md ) subtypes).
128
+ ``` kotlin
129
+ when (x) { .. . }
130
+ ```
131
+
132
+ </td >
133
+ <td >
134
+
135
+ ``` kotlin
136
+ when { .. . }
137
+ ```
138
+
139
+ </td >
140
+ </tr >
141
+ </table >
142
+
143
+ Depending on how you use ` when ` , there are different requirements for whether you need to cover all possible cases in your
144
+ branches.
145
+
146
+ If you use ` when ` as a statement, you don't have to cover all possible cases. In this example, some cases aren't covered,
147
+ so nothing happens. However, no error occurs:
148
+
149
+ ``` kotlin
150
+ fun main () {
151
+ // sampleStart
152
+ val x = 3
153
+ when (x) {
154
+ // Not all cases are covered
155
+ 1 -> print (" x == 1" )
156
+ 2 -> print (" x == 2" )
157
+ }
158
+ // sampleEnd
159
+ }
160
+ ```
161
+ {kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="kotlin-when-statement"}
162
+
163
+ In a ` when ` statement, the values of individual branches are ignored. Just like with ` if ` , each branch can be a block,
164
+ and its value is the value of the last expression in the block.
165
+
166
+ If you use ` when ` as an expression, you have to cover all possible cases. In other words, it must be _ exhaustive_ .
167
+ The value of the first matching branch becomes the value of the overall expression. If you don't cover all cases,
168
+ the compiler throws an error.
169
+
170
+ If your ` when ` expression has a subject, you can use an ` else ` branch to make sure that all possible cases are covered, but
171
+ it isn't mandatory. For example, if your subject is a ` Boolean ` , [ ` enum ` class] ( enum-classes.md ) , [ ` sealed ` class] ( sealed-classes.md ) ,
172
+ or one of their nullable counterparts, you can cover all cases without an ` else ` branch:
80
173
81
174
``` kotlin
82
175
enum class Bit {
83
176
ZERO , ONE
84
177
}
85
178
86
179
val numericValue = when (getRandomBit()) {
180
+ // No else branch is needed because all cases are covered
87
181
Bit .ZERO -> 0
88
182
Bit .ONE -> 1
89
- // 'else' is not required because all cases are covered
90
183
}
91
184
```
92
185
93
- In ` when ` _ statements_ , the ` else ` branch is mandatory in the following conditions:
94
- * ` when ` has a subject of a ` Boolean ` , [ ` enum ` ] ( enum-classes.md ) ,
95
- or [ ` sealed ` ] ( sealed-classes.md ) type, or their nullable counterparts.
96
- * branches of ` when ` don't cover all possible cases for this subject.
186
+ If your ` when ` expression ** doesn't** have a subject, you ** must** have an ` else ` branch or the compiler throws an error.
187
+ The ` else ` branch is evaluated when none of the other branch conditions are satisfied:
97
188
98
189
``` kotlin
99
- enum class Color {
100
- RED , GREEN , BLUE
101
- }
102
-
103
- when (getColor()) {
104
- Color .RED -> println (" red" )
105
- Color .GREEN -> println (" green" )
106
- Color .BLUE -> println (" blue" )
107
- // 'else' is not required because all cases are covered
108
- }
109
-
110
- when (getColor()) {
111
- Color .RED -> println (" red" ) // no branches for GREEN and BLUE
112
- else -> println (" not red" ) // 'else' is required
190
+ when {
191
+ a > b -> " a is greater than b"
192
+ a < b -> " a is less than b"
193
+ else -> " a is equal to b"
113
194
}
114
195
```
115
196
197
+ ` when ` expressions and statements offer different ways to simplify your code, handle multiple conditions, and perform
198
+ type checks.
116
199
117
- To define a common behavior for multiple cases, combine their conditions in a single line with a comma:
200
+ You can define a common behavior for multiple cases by combining their conditions in a single line with a comma:
118
201
119
202
``` kotlin
120
203
when (x) {
@@ -123,7 +206,7 @@ when (x) {
123
206
}
124
207
```
125
208
126
- You can use arbitrary expressions (not only constants) as branch conditions
209
+ You can use arbitrary expressions (not only constants) as branch conditions:
127
210
128
211
``` kotlin
129
212
when (x) {
@@ -132,7 +215,7 @@ when (x) {
132
215
}
133
216
```
134
217
135
- You can also check a value for being ` in ` or ` !in ` a [ range] ( ranges.md ) or a collection:
218
+ You can also check whether a value is or isn't contained in a [ range] ( ranges.md ) or collection via the ` in ` or ` !in ` keywords :
136
219
137
220
``` kotlin
138
221
when (x) {
@@ -143,9 +226,9 @@ when (x) {
143
226
}
144
227
```
145
228
146
- Another option is checking that a value ` is ` or ` !is ` of a particular type . Note that,
147
- due to [ smart casts] ( typecasts.md#smart-casts ) , you can access the methods and properties of the type without
148
- any extra checks.
229
+ Additionally, you can check that a value is or isn't a particular type via the ` is ` or ` !is ` keywords . Note that,
230
+ due to [ smart casts] ( typecasts.md#smart-casts ) , you can access the member functions and properties of the type without
231
+ any additional checks.
149
232
150
233
``` kotlin
151
234
fun hasPrefix (x : Any ) = when (x) {
@@ -154,8 +237,8 @@ fun hasPrefix(x: Any) = when(x) {
154
237
}
155
238
```
156
239
157
- ` when ` can also be used as a replacement for an ` if ` -` else ` ` if ` chain.
158
- If no argument is supplied , the branch conditions are simply boolean expressions, and a branch is executed when its condition is true:
240
+ You can use ` when ` as a replacement for an ` if ` -` else ` ` if ` chain.
241
+ If there's no subject , the branch conditions are simply boolean expressions, and a branch is run when its condition is true:
159
242
160
243
``` kotlin
161
244
when {
@@ -165,7 +248,7 @@ when {
165
248
}
166
249
```
167
250
168
- You can capture * when * subject in a variable using following syntax:
251
+ You can capture the subject in a variable by using the following syntax:
169
252
170
253
``` kotlin
171
254
fun Request.getBody () =
@@ -175,7 +258,7 @@ fun Request.getBody() =
175
258
}
176
259
```
177
260
178
- The scope of variable introduced in * when * subject is restricted to the body of this * when* .
261
+ The scope of a variable introduced as the subject is restricted to the body of the ` when ` expression or statement .
179
262
180
263
## For loops
181
264
@@ -208,11 +291,12 @@ To iterate over a range of numbers, use a [range expression](ranges.md):
208
291
fun main () {
209
292
// sampleStart
210
293
for (i in 1 .. 3 ) {
211
- println (i)
294
+ print (i)
212
295
}
213
296
for (i in 6 downTo 0 step 2 ) {
214
- println (i)
297
+ print (i)
215
298
}
299
+ // 1236420
216
300
// sampleEnd
217
301
}
218
302
```
@@ -227,8 +311,9 @@ fun main() {
227
311
val array = arrayOf(" a" , " b" , " c" )
228
312
// sampleStart
229
313
for (i in array.indices) {
230
- println (array[i])
314
+ print (array[i])
231
315
}
316
+ // abc
232
317
// sampleEnd
233
318
}
234
319
```
@@ -243,18 +328,21 @@ fun main() {
243
328
for ((index, value) in array.withIndex()) {
244
329
println (" the element at $index is $value " )
245
330
}
331
+ // the element at 0 is a
332
+ // the element at 1 is b
333
+ // the element at 2 is c
246
334
// sampleEnd
247
335
}
248
336
```
249
337
{kotlin-runnable="true" kotlin-min-compiler-version="1.3"}
250
338
251
339
## While loops
252
340
253
- ` while ` and ` do-while ` loops execute their body continuously while their condition is satisfied.
341
+ ` while ` and ` do-while ` loops process their body continuously while their condition is satisfied.
254
342
The difference between them is the condition checking time:
255
- * ` while ` checks the condition and, if it's satisfied, executes the body and then returns to the condition check.
256
- * ` do-while ` executes the body and then checks the condition. If it's satisfied, the loop repeats. So, the body of ` do-while `
257
- executes at least once regardless of the condition.
343
+ * ` while ` checks the condition and, if it's satisfied, processes the body and then returns to the condition check.
344
+ * ` do-while ` processes the body and then checks the condition. If it's satisfied, the loop repeats. So, the body of ` do-while `
345
+ runs at least once regardless of the condition.
258
346
259
347
``` kotlin
260
348
while (x > 0 ) {
0 commit comments