0
0
Kotlinprogramming~5 mins

Enum with when exhaustive check in Kotlin

Choose your learning style9 modes available
Introduction
Enums help group related values. Using when with enums lets you handle all cases clearly and safely.
When you have a fixed set of options, like days of the week or directions.
When you want to run different code for each option in a clear way.
When you want the compiler to warn you if you forget to handle a case.
When you want your code to be easy to read and maintain.
When you want to avoid mistakes by handling all enum values explicitly.
Syntax
Kotlin
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"
}
The when expression covers all enum values, so no else branch is needed.
If you miss a case, the compiler will show an error, helping you catch mistakes early.
Examples
Handles all traffic light colors with clear actions.
Kotlin
enum class Light {
    RED, YELLOW, GREEN
}

fun action(light: Light) = when(light) {
    Light.RED -> "Stop"
    Light.YELLOW -> "Get ready"
    Light.GREEN -> "Go"
}
Different messages for each mood using when with enum.
Kotlin
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"
}
Sample Program
This program prints an activity for each season. The when expression covers all seasons, so it is safe and clear.
Kotlin
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)}")
    }
}
OutputSuccess
Important Notes
Always cover all enum cases in when to avoid needing an else branch.
The compiler helps by showing errors if you miss any enum value.
This makes your code safer and easier to understand.
Summary
Enums group fixed related values like directions or states.
Using when with enums lets you handle each case clearly.
The compiler checks that you cover all enum values, preventing mistakes.