When-statement with enums

suggest change

when can be used to match enum values:

enum class Day {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

fun doOnDay(day: Day) {
    when (day) {
        Day.Sunday -> { /* Do something */ }
        Day.Monday, Day.Tuesday -> { /* Do another thing */ }
        Day.Wednesday -> { /* ... */ }
        Day.Thursday -> { /* ... */ }
        Day.Friday -> { /* ... */ }
        Day.Saturday -> { /* ... */ }
    }
}

As you can see in the second branch (Monday and Tuesday), two or more enum values can be combined.

If your cases are not exhaustive, the compiler reports an error. You can use else to handle the remaining cases:

fun doOnDay(day: Day) {
    when (day) {
        Day.Monday -> { /* Work */ }
        Day.Tuesday -> { /* Work hard */ }
        Day.Wednesday -> { /* ... */ }
        Day.Thursday -> { /* ... */ }
        Day.Friday -> { /* ... */ }
        else -> { /* Party on the weekend */ }
    }
}

The same can be done with an if/else chain, but when checks for missing enum values and reads more naturally.

See Enum and the enum topic for more about Kotlin enums.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents