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 other thing
        Day.Wednesday ->  // ...
        Day.Thursday ->   // ...
        Day.Friday ->     // ...
        Day.Saturday ->   // ...
    }
}

As you can see in second case line (Monday and Tuedsay) it is also possible to combine two or more enum values.

If your cases are not exhaustive the compile will show an error. You can use else to handle default cases:

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

Though the same can be done using if-then-else construct, when takes care of missing enum values and makes it more natural.

Check here for more information about kotlin enum

Feedback about page:

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



Table Of Contents