Kotlin’s when expression selects one branch from several alternatives and returns that branch’s value. It often replaces Java’s switch, avoids fall-through, and supports expression-body functions. section 2.3 section 2.3.2
Match enum values
fun getMnemonic(color: Color) = when (color) { Color.RED -> "Richard" Color.ORANGE -> "Of" Color.YELLOW -> "York" Color.GREEN -> "Gave" Color.BLUE -> "Battle" Color.INDIGO -> "In" Color.VIOLET -> "Vain" } Each branch uses an arrow and produces a value; no break statements are needed. Multiple values can share one branch, such as RED, ORANGE, YELLOW. section 2.3.2
Use the form that best expresses the decision:
- Capture the subject inside when to keep a temporary variable local to the expression: when (val color = measureColor()) { ... }. The captured value remains available in branch bodies. section 2.3.3
- Match arbitrary objects with equality conditions, such as setOf(c1, c2), and add else when the compiler cannot establish exhaustiveness. section 2.3.4
- Omit the argument when each branch is a Boolean expression. This can avoid temporary Set objects, although explicit conditions may be harder to read. section 2.3.5
- Match types with branches such as is Num and is Sum; Kotlin applies smart casts so branch code can access the checked value without explicit casts. section 2.3.7
- Use a block for compound branch actions. The block’s last expression becomes the branch result, allowing logging, local values, and recursive computation. section 2.3.8
Listing 2.16 Using when without an argument
fun mixOptimized(c1: Color, c2: Color) =
when { #1
(c1 == RED && c2 == YELLOW) ||
(c1 == YELLOW && c2 == RED) ->
ORANGE
(c1 == YELLOW && c2 == BLUE) ||
(c1 == BLUE && c2 == YELLOW) ->
GREEN
(c1 == BLUE && c2 == VIOLET) ||
(c1 == VIOLET && c2 == BLUE) ->
INDIGO
else -> throw Exception("Dirty color") #2
}
fun main() {
println(mixOptimized(BLUE, YELLOW))
// GREEN
}
Compare a subjectless when with Boolean conditions, grouped alternatives, and an else branch in an optimized color-mixing function. section 2.3.5
