October 2021
Intermediate to advanced
500 pages
16h 23m
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, and it executes corresponding code if 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 a player can be a member of a fantasy race, like an orc or a 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: String = when (race) { "dwarf" -> "Keepers of the Mines" "gnome" -> "Tinkerers of the Underground" "orc", "human" ...Read now
Unlock full access