What if your code could warn you every time you forget to handle a case?
Why Enum with when exhaustive check in Kotlin? - Purpose & Use Cases
Imagine you have a list of tasks, each with a status like "To Do", "In Progress", or "Done". You want to write code that does something different for each status. Without enums and exhaustive checks, you might write many if-else statements, and it's easy to forget one status or add a new one and miss updating your code.
Manually checking each status with if-else is slow and error-prone. You might forget a case, causing bugs that are hard to find. When you add a new status, you have to hunt through your code to update every check. This makes your code fragile and hard to maintain.
Using enums with a when expression that is exhaustive means Kotlin forces you to handle every possible status. If you miss one, the compiler will warn you. This makes your code safer, easier to read, and easier to update when you add new statuses.
if (status == "To Do") { /*...*/ } else if (status == "In Progress") { /*...*/ } // forgot "Done" case
when (status) {
Status.TODO -> /*...*/
Status.IN_PROGRESS -> /*...*/
Status.DONE -> /*...*/
}This lets you write clear, safe code that automatically reminds you to handle every possible case, preventing bugs before they happen.
Think of a traffic light system with states like RED, YELLOW, and GREEN. Using enums with exhaustive when ensures your program reacts correctly to every light color, and if a new color is added, you won't forget to update your logic.
Manual checks can miss cases and cause bugs.
Enums with exhaustive when force you to handle all cases.
This leads to safer, clearer, and easier-to-maintain code.