when Expressions

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" ...

Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.