Control Flow: if, when, and Ranges
if as an expression
In Kotlin, if can directly produce a value, no separate ternary operator needed:
val xp = 45
val message = if (xp >= 50) "Level up!" else "Keep going"
when
when is Kotlin's replacement for switch, and it's far more flexible, it can match exact values, ranges, types, or arbitrary conditions:
val tier = when {
xp >= 100 -> "Platinum"
xp >= 50 -> "Gold"
xp >= 25 -> "Silver"
else -> "Bronze"
}
val dayName = when (3) {
1, 7 -> "Weekend"
in 2..6 -> "Weekday"
else -> "Invalid"
}
Each branch uses ->, and when doesn't fall through to the next branch the way older switch statements in other languages can, only the first matching branch runs.
Ranges and loops
for (i in 1..5) {
println("Iteration $i")
}
for (i in 10 downTo 1 step 2) {
println(i) // 10, 8, 6, 4, 2
}
val scores = listOf(90, 85, 77)
for (score in scores) {
println(score)
}
var tries = 0
while (tries < 3) {
tries++
}
1..5 creates a range, an inclusive sequence of values, downTo counts backward, and step changes the increment. for (score in scores) reads as "for each score in scores", the idiomatic way to iterate a collection.