This Week I Learned: Kotlin sealed classes [2022–04–15]
Kotlin’s sealed classes are pretty cool. They let you write code that is terser and more correct, because the compiler knows that you have or have not enumerated every possible branch.
Some examples:
- handling every possible numeric value
- handling every possible subclass
Who hasn’t wanted to know that they’ve covered every possible edge case?
(Have a read of Kotlin’s when expression before parsing the following code in your head.)
Here is some before code from a learning exercise that I did:
I had to write that extra else line. Could I have left it out, forgetting to handle other cases? No: if I leave open the possibility of someone else implementing my interface (or extending my class if I’d gone that way) then the compiler will tell me:
Here’s a second version that uses a sealed interface:
Look, 1 fewer line of code and it’s safer.
The sealed
keyword works with classes and interfaces. Check it out.