Skip to content

Control flow

if runs a block when a condition holds, and else when it doesn’t.

val health = 3
if (health < 5) {
Logger.info("Low health.")
} else {
Logger.info("Healthy.")
}

An if with an else gives back the value of the branch it took.

val coins = 80
val price = 100
val message = if (coins >= price) "Sold." else "Not enough coins."

when (x) compares x with each branch. A branch can list several values.

val option = "Trade"
val reply = when (option) {
"Talk-to" -> "Hello there."
"Trade", "Buy" -> "Take a look."
else -> "I can't do that."
}

A branch can test in a range or is a type.

fun rank(level: Int) = when (level) {
in 1..9 -> "Beginner"
in 10..49 -> "Skilled"
else -> "Expert"
}
fun describe(drop: Any) = when (drop) {
is Int -> "$drop coins"
is String -> "a $drop"
else -> "something"
}

With no subject, each branch is a condition. The first true one wins.

val hour = 21
val greeting = when {
hour < 12 -> "Good morning"
hour < 18 -> "Good afternoon"
else -> "Good evening"
}

for goes over a list, a set, a map or a range.

val party = listOf("Ana", "Bo", "Cy")
for (member in party) {
Logger.info("$member joined.")
}

withIndex() gives each item with its position. indices gives just the positions.

val podium = listOf("Ana", "Bo", "Cy")
for ((place, name) in podium.withIndex()) {
Logger.info("${place + 1}. $name")
}

Each entry has a key and a value.

val stock = mapOf("bread" to 12, "cake" to 3)
for ((item, count) in stock) {
Logger.info("$count $item left")
}

a..b counts from a to b. a..<b stops before b. downTo counts down, and step skips.

for (wave in 1..5) Logger.info("Wave $wave")
for (slot in 0..<28) Logger.info("Slot $slot")
for (n in 10 downTo 0 step 2) Logger.info("$n")

in checks whether a value is in a range or a collection. !in checks that it isn’t.

val level = 35
val banned = setOf("griefer")
val canEnter = level in 30..99 && "Ana" !in banned

while checks before each pass. do-while checks after, so it runs at least once.

var hits = 0
while (hits < 3) {
hits++
}
var tries = 0
do {
tries++
} while (tries < 3)

break leaves a loop. continue skips to its next pass.

val drops = listOf("bones", "junk", "coins", "stop", "gem")
for (drop in drops) {
if (drop == "junk") continue
if (drop == "stop") break
Logger.info("Picked up $drop")
}

A label, name@, lets break and continue reach an outer loop.

val grid = listOf(listOf(0, 0), listOf(0, 7))
search@ for (row in grid) {
for (cell in row) {
if (cell == 7) break@search
}
}

return@name leaves a block early. The name is the function the block was given to, such as a hook.

on_login { player ->
val hour = java.time.LocalTime.now().hour
if (hour < 6) return@on_login
player.message("Welcome back.")
}
listOf(1, 2, 3).forEach {
if (it == 2) return@forEach
Logger.info("$it")
}

throw raises an error. try and catch handle it, and finally always runs.

fun buy(coins: Int, price: Int): Int {
if (coins < price) throw IllegalArgumentException("Not enough coins")
return coins - price
}
try {
buy(10, 50)
} catch (e: IllegalArgumentException) {
Logger.warn("Purchase failed: ${e.message}")
} finally {
Logger.info("Shop closed.")
}

try gives back the value of its block, or of the catch that ran.

val typed = "12x"
val amount = try { typed.toInt() } catch (e: NumberFormatException) { 0 }