+85
Kotlin/ControlFlow.org
+85
Kotlin/ControlFlow.org
···
1
+
* Control Flow
2
+
3
+
** Conditional expressions
4
+
5
+
Kotlin provides =if= and =when= for checking conditional expressions
6
+
7
+
*** When
8
+
9
+
Use =when= when you have a conditional expressions with multiple branches.
10
+
=when= can be used either as a statement or as an expression.
11
+
12
+
Heres how to use:
13
+
14
+
+ Place the conditional expression within parentheses =()= and the actions to take within curly braces ={}=
15
+
+ Use =->= in each branch to separate each condition from each action
16
+
17
+
#+begin_src kotlin
18
+
val obj = "Hello"
19
+
20
+
when (obj) {
21
+
"1" -> println("One")
22
+
"Hello" -> println("Greeting")
23
+
else -> println("Unknown")
24
+
}
25
+
#+end_src
26
+
27
+
#+RESULTS:
28
+
: Greeting
29
+
30
+
Here's an example of using =when= as an expression, the syntax is assigned immediately to a variable:
31
+
32
+
#+begin_src kotlin
33
+
val result = when (obj) {
34
+
"1" -> "One"
35
+
"Hello" -> "Greeting"
36
+
else -> "Unknown"
37
+
}
38
+
39
+
println(result)
40
+
#+end_src
41
+
42
+
#+RESULTS:
43
+
: Greeting
44
+
45
+
If =when= is used as an expression, the else branch is mandatory, unless the compiler can detect
46
+
that all possible cases are covered by the branch conditions.
47
+
48
+
The previous example showed that =when= is useful for matching a variable.
49
+
=when= is also useful when you need to check a chain of Boolean expressions
50
+
51
+
#+begin_src kotlin
52
+
val temp = 18
53
+
54
+
val description = when {
55
+
temp < 0 -> "very cold"
56
+
temp < 10 -> "a bit cold"
57
+
temp < 20 -> "warm"
58
+
else -> "hot"
59
+
}
60
+
61
+
println(description)
62
+
#+end_src
63
+
64
+
#+RESULTS:
65
+
: warm
66
+
67
+
68
+
** Ranges
69
+
70
+
The most commom way to create a range in Kotlin is to use the =..= operator.
71
+
For example, =1..4= is equivalent to =1, 2, 3, 4=.
72
+
73
+
To declare a range that doesn't include the end value, use the =..<= operator.
74
+
For example, =1..<4= is equivalent to =1, 2, 3=.
75
+
76
+
To declare a range in reverse order, use =downTo=.
77
+
For example, =4 downTo 1= is equivalent to =4, 3, 2, 1=.
78
+
79
+
To declare a range that increments in a step, use =step= and the desired increment value.
80
+
For example, =1..5 step 2= is equivalent to =1, 3, 5=.
81
+
82
+
You can also do the same with =Char= ranges:
83
+
84
+
+ ='a'..'d'= = ='a', 'b', 'c', 'd'=
85
+
+ ='z' downTo 's' step 2= = ='z', 'x', 'v', 't'=