What if your code could warn you every time you forget to handle a new case?
Why Sealed classes with when exhaustive check in Kotlin? - Purpose & Use Cases
Imagine you have a list of different types of animals, and you want to write code that handles each type separately. You try to check each animal type manually with many if-else statements.
This manual approach is slow and error-prone because you might forget to handle a new animal type added later. Your code becomes messy and hard to maintain, leading to bugs.
Sealed classes let you define a fixed set of types in one place. When you use a when expression with sealed classes, Kotlin forces you to handle all possible cases. This makes your code safer and easier to read.
if (animal is Dog) { /* handle dog */ } else if (animal is Cat) { /* handle cat */ } // what if new animal added?
when (animal) {
is Dog -> /* handle dog */
is Cat -> /* handle cat */
// compiler ensures all cases handled
}You can write clear, safe code that automatically checks you cover all possible cases, preventing bugs before they happen.
In a messaging app, you might have sealed classes for message types like Text, Image, and Video. Using when with sealed classes ensures you handle every message type properly.
Manual checks can miss new cases and cause bugs.
Sealed classes define a fixed set of types clearly.
when with sealed classes forces exhaustive checks for safety.