Control Flow
If/else
Section titled “If/else”Works as both a statement and an expression:
// Statementif (x > 0) { println("positive")} else { println("non-positive")}
// Expression (returns a value)val abs = if (x >= 0) x else -xElse-if chains
Section titled “Else-if chains”if (score >= 90) { println("A")} else if (score >= 80) { println("B")} else if (score >= 70) { println("C")} else { println("F")}Pattern matching with optional subject:
// With subjectwhen (day) { 1 -> println("Monday") 2 -> println("Tuesday") 6, 7 -> println("Weekend") else -> println("Other")}
// Without subject (acts as if/else chain)when { temperature < 0 -> println("freezing") temperature < 20 -> println("cold") else -> println("warm")}Range patterns
Section titled “Range patterns”when (score) { in 90..100 -> println("A") in 80..89 -> println("B") in 70..79 -> println("C") else -> println("F")}When as expression
Section titled “When as expression”val label = when (n) { 0 -> "zero" 1 -> "one" else -> "many"}Nested when
Section titled “Nested when”when (category) { "fruit" -> when (name) { "apple" -> println("red") "banana" -> println("yellow") else -> println("unknown fruit") } else -> println("not a fruit")}For loops
Section titled “For loops”Iterate over integer ranges:
for (i in 1..10) { println(i)}While loops
Section titled “While loops”var i = 0while (i < 10) { println(i) i += 1}Do-while loops
Section titled “Do-while loops”var input = ""do { println("enter 'quit' to exit") // ... read input ...} while (input != "quit")Break and continue
Section titled “Break and continue”for (i in 1..100) { if (i % 15 == 0) continue if (i > 50) break println(i)}break and continue work inside for, while, and do-while loops,
including when nested inside if blocks within the loop body.
in Operator
Section titled “in Operator”Check containment in ranges and collections:
val r = 1..10println(5 in r) // trueprintln(11 in r) // falseprintln(r.first) // 1println(r.last) // 10The in operator desugars to collection.contains(element). The !in operator negates the result.
Return
Section titled “Return”Early return from functions:
fun findFirst(items: Int): Int { if (items <= 0) return -1 // ... rest of function ... return items}