Introduction
Enums help group related values. Using when with enums lets you handle all cases clearly and safely.
enum class Direction { NORTH, SOUTH, EAST, WEST } fun describe(direction: Direction) = when(direction) { Direction.NORTH -> "Going north" Direction.SOUTH -> "Going south" Direction.EAST -> "Going east" Direction.WEST -> "Going west" }
enum class Light { RED, YELLOW, GREEN } fun action(light: Light) = when(light) { Light.RED -> "Stop" Light.YELLOW -> "Get ready" Light.GREEN -> "Go" }
enum class Mood { HAPPY, SAD, ANGRY } fun moodMessage(mood: Mood) = when(mood) { Mood.HAPPY -> "Smile!" Mood.SAD -> "Cheer up!" Mood.ANGRY -> "Take a deep breath" }
enum class Season { SPRING, SUMMER, FALL, WINTER } fun seasonActivity(season: Season) = when(season) { Season.SPRING -> "Plant flowers" Season.SUMMER -> "Go swimming" Season.FALL -> "Pick apples" Season.WINTER -> "Build a snowman" } fun main() { for (s in Season.values()) { println("In $s: ${seasonActivity(s)}") } }
when expression require when used with an enum class?when expression can check these values.when to be exhaustive, avoiding missing cases.when expression that exhaustively checks all values of this enum?enum class Direction { NORTH, SOUTH, EAST, WEST }enum class Light { RED, GREEN, YELLOW }
fun signalMessage(light: Light) = when(light) {
Light.RED -> "Stop"
Light.GREEN -> "Go"
Light.YELLOW -> "Caution"
}
fun main() {
println(signalMessage(Light.YELLOW))
}Light.YELLOW.Light.YELLOW.enum class Status { SUCCESS, ERROR, LOADING }
fun getStatusMessage(status: Status) = when(status) {
Status.SUCCESS -> "Done"
Status.ERROR -> "Failed"
}
Status.SUCCESS and Status.ERROR are handled; Status.LOADING is missing.getDayType to use an exhaustive when expression without an else branch?enum class Day { MON, TUE, WED, THU, FRI, SAT, SUN }
fun getDayType(day: Day): String = when(day) {
Day.SAT, Day.SUN -> "Weekend"
Day.MON, Day.TUE, Day.WED, Day.THU, Day.FRI -> "Weekday"
}when exhaustive if all enum cases are explicitly covered across branches, even when grouped with commas in the same branch. No else branch is needed.Pass the test and this pattern moves unknown