Kotlin: Control flow – code examples
if / when
Use case: React differently, e.g. compute grades or price tiers.
fun main() {
val punkte = 73
val note = when {
punkte >= 90 -> "very good"
punkte >= 70 -> "good"
else -> "needs improvement"
}
println(note)
}when without an argument is the Kotlin counterpart to if / else if; since it is an expression, it directly yields the value for note.
for Loops
Use case: Process every element of a list or repeat n times.
fun main() {
for (i in 0 until 3) {
println("Round $i")
}
for (frucht in listOf("Apple", "Pear")) {
println(frucht)
}
}0 until 3 is a range from 0 to 2; the second loop runs directly over the list.
when with Types
Control flow#when#is#smartcast
Use case: Handle values of different types (JSON, events, messages) differently.
fun beschreibe(x: Any): String = when (x) {
0 -> "Zero"
is Int -> if (x > 0) "positive number" else "negative number"
is String -> "Text with ${x.length} characters"
is List<*> -> "List with ${x.size} elements"
else -> "unknown"
}
fun main() {
listOf(0, 5, "Kotlin", listOf(1, 2), 3.5).forEach { println(beschreibe(it)) }
}After is, the smart cast applies: inside is String you can use x.length directly. Output: Zero, positive number, Text with 6 characters, List with 2 elements, unknown.