Kotlin Control Flow
Conditionals and loops in Kotlin
If Expression
val max = if (a > b) a else b # if as expression
val result = if (a > b) {
println("a is greater")
a # last expression is returned
} else {
println("b is greater")
b
}
When Expression
when (x) { # switch replacement
1 -> println("One")
2, 3 -> println("Two or Three") # multiple values
in 4..10 -> println("Range") # range check
else -> println("Other") # default case
}
For Loop
for (i in 1..5) { # range 1 to 5
println(i)
}
for (i in 1 until 5) { } # 1 to 4
for (i in 5 downTo 1) { } # reverse
for (i in 1..10 step 2) { } # step by 2
While Loop
while (condition) { # repeat while true
// code
}
do { # execute at least once
// code
} while (condition)
Loop Control
break # exit loop
continue # skip to next iteration
return # exit function