Control Flow
## Learning Objectives
- Master if expressions
- Understand when expressions
- Work with loops (for, while, do-while)
- Use ranges and iterations
## If Expressions
### Basic if
```kotlin
fun main() {
val a = 10
val b = 20
if (a < b) {
println("a is less than b")
}
}
```
### If-else
```kotlin
fun main() {
val a = 10
val b = 5
if (a > b) {
println("a is greater")
} else {
println("b is greater or equal")
}
}
```
### If-else-if Chain
```kotlin
fun main() {
val num = 0
if (num > 0) {
println("Positive")
} else if (num < 0) {
println("Negative")
} else {
println("Zero")
}
}
```
### If as an Expression
In Kotlin, if can return a value:
```kotlin
fun main() {
val a = 10
val b = 20
val max = if (a > b) a else b
println("Max: $max") // 20
}
```
### Block Body in If Expression
```kotlin
fun main() {
val a = 10
val b = 20
val max = if (a > b) {
println("Choosing a")
a
} else {
println("Choosing b")
b
}
println("Max: $max")
}
```
## When Expression
### Basic when
```kotlin
fun main() {
val x = 1
when (x) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
else -> println("Unknown")
}
}
```
### when as Expression
```kotlin
fun main() {
val x = 2
val result = when (x) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Unknown"
}
println("Result: $result")
}
```
### Multiple Values
```kotlin
fun main() {
val grade = 'B'
val score = when (grade) {
'A' -> 90..100
'B' -> 80..89
'C' -> 70..79
'D' -> 60..69
'F' -> 0..59
else -> null
}
println("Score range: $score")
}
```
### Using when without Argument
```kotlin
fun main() {
val num = 15
when {
num < 0 -> println("Negative")
num == 0 -> println("Zero")
num % 2 == 0 -> println("Even positive")
else -> println("Odd positive")
}
}
```
### Type Checking with when
```kotlin
fun main() {
val obj: Any = "Hello"
when (obj) {
is Int -> println("Integer: ${obj * 2}")
is String -> println("String length: ${obj.length}")
is Double -> println("Double: ${obj}")
else -> println("Unknown type")
}
}
```
## Ranges
### Creating Ranges
```kotlin
fun main() {
// Closed range inclusive
val range1 = 1..10
// Downward range
val range2 = 10 downTo 1
// With step
val range3 = 0..10 step 2
// Until (exclusive end)
val range4 = 0 until 10
println(range1)
println(range2)
println(range3)
println(range4)
}
```
### Iterating Over Ranges
```kotlin
fun main() {
println("1..5:")
for (i in 1..5) {
print("$i ")
}
println()
println("\n5 downTo 1:")
for (i in 5 downTo 1) {
print("$i ")
}
println()
println("\n0 until 5:")
for (i in 0 until 5) {
print("$i ")
}
println()
println("\n0..10 step 2:")
for (i in 0..10 step 2) {
print("$i ")
}
}
```
## For Loops
### Basic for Loop
```kotlin
fun main() {
val items = listOf("apple", "banana", "cherry")
for (item in items) {
println(item)
}
}
```
### For Loop with Index
```kotlin
fun main() {
val items = listOf("apple", "banana", "cherry")
for (index in items.indices) {
println("Item at $index: ${items[index]}")
}
// Or with withIndex()
println()
for ((index, value) in items.withIndex()) {
println("Item at $index: $value")
}
}
```
### Iterating Over Maps
```kotlin
fun main() {
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
for ((key, value) in map) {
println("$key -> $value")
}
}
```
### For Loop with Ranges
```kotlin
fun main() {
// Iterate 0 to 9
for (i in 0 until 10) {
print("$i ")
}
println()
// Iterate with step
for (i in 0..10 step 2) {
print("$i ")
}
println()
// Reverse
for (i in 10 downTo 0) {
print("$i ")
}
}
```
## While Loops
### Basic while
```kotlin
fun main() {
var i = 0
while (i < 5) {
println("i = $i")
i++
}
}
```
### do-while Loop
```kotlin
fun main() {
var i = 0
do {
println("i = $i")
i++
} while (i < 5)
}
```
### while with Break
```kotlin
fun main() {
var count = 0
while (true) {
count++
if (count > 10) {
break
}
}
println("Count: $count")
}
```
## Continue
```kotlin
fun main() {
for (i in 1..10) {
if (i % 2 == 0) {
continue // Skip even numbers
}
print("$i ")
}
println()
// Output: 1 3 5 7 9
}
```
## Nested Loops and Labels
### Labels
```kotlin
fun main() {
outer@ for (i in 1..3) {
inner@ for (j in 1..3) {
println("i=$i, j=$j")
if (i == 2) {
break@outer // Break outer loop
}
}
}
}
```
### Continue with Labels
```kotlin
fun main() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) {
continue@outer
}
println("i=$i, j=$j")
}
}
}
```
## Return from Loops
### Using return with Labels
```kotlin
fun main() {
loop@ for (i in 1..10) {
for (j in 1..10) {
if (i == 2 && j == 2) {
println("Found at i=$i, j=$j")
break@loop
}
}
}
println("Done")
}
```
## Summary
- If expressions can return values and are expressions in Kotlin
- When is more powerful than switch - handles multiple values, ranges, types
- Use `..` for inclusive range, `until` for exclusive end
- `downTo` creates reverse ranges, `step` changes increment
- For loops iterate over collections, ranges, maps with index
- While and do-while loops similar to other languages
- Labels (`@`) allow breaking/continuing specific nested loops
- `break` exits loop, `continue` skips to next iteration
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →