July 2018
Intermediate to advanced
400 pages
12h 14m
English
The when expression is another control flow mechanism available in Kotlin.
Like if/else, the when expression allows you to write conditions to check for and will execute corresponding code when the condition evaluates as true.
when provides a more concise syntax and is an especially good fit for conditionals with three or more branches.
Suppose that in NyetHack, players can be members of several different fantasy races, like orc or gnome, and those fantasy races ally with each other in factions.
This when expression takes in a fantasy race and returns the name of the faction to which it belongs:
val race = "gnome" val faction = when (race) { "dwarf" -> "Keepers of the Mines" "gnome" -> "Keepers of the Mines" "orc" ...