Skip to content
skotch
...

Control Flow

Works as both a statement and an expression:

// Statement
if (x > 0) {
println("positive")
} else {
println("non-positive")
}
// Expression (returns a value)
val abs = if (x >= 0) x else -x
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 subject
when (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")
}
when (score) {
in 90..100 -> println("A")
in 80..89 -> println("B")
in 70..79 -> println("C")
else -> println("F")
}
val label = when (n) {
0 -> "zero"
1 -> "one"
else -> "many"
}
when (category) {
"fruit" -> when (name) {
"apple" -> println("red")
"banana" -> println("yellow")
else -> println("unknown fruit")
}
else -> println("not a fruit")
}

Iterate over integer ranges:

for (i in 1..10) {
println(i)
}
var i = 0
while (i < 10) {
println(i)
i += 1
}
var input = ""
do {
println("enter 'quit' to exit")
// ... read input ...
} while (input != "quit")
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.

Check containment in ranges and collections:

val r = 1..10
println(5 in r) // true
println(11 in r) // false
println(r.first) // 1
println(r.last) // 10

The in operator desugars to collection.contains(element). The !in operator negates the result.

Early return from functions:

fun findFirst(items: Int): Int {
if (items <= 0) return -1
// ... rest of function ...
return items
}