I see a lot of modern Kotlin code using Sealed Classes for state management (like Loading, Success, Error). What is the functional advantage of this over a traditional Enum? Does it impact performance, and how does it improve the 'when' expression usage in complex logic?
3 answers
The primary advantage of Sealed Classes over Enums is that subclasses can have multiple instances and hold their own state. Enums are restricted to a single instance for each type. For example, in a "Success" state, a Sealed Class can hold the specific data returned from an API, while an "Error" state can hold a specific exception object. With Enums, you can't do that. When used with a when expression, the compiler ensures you’ve covered every possible subclass, making your code "exhaustively" safe. This prevents bugs where you add a new state but forget to update the UI logic.
Does the use of Sealed Classes increase the size of the compiled DEX file significantly in Android apps, or is the overhead negligible compared to Enums?
Sealed interfaces are also a thing now in newer Kotlin versions! They allow even more flexibility when you need to implement multiple restricted hierarchies.
Good catch, Jennifer. Sealed interfaces have been a lifesaver for us when we need to share behavior across different sealed hierarchies without the limitations of class inheritance.
Charles, while Sealed Classes do generate a bit more bytecode than a simple Enum, the impact on DEX size is negligible in any modern application. The safety and readability benefits far outweigh the couple of kilobytes added. If you are really worried about size, R8/ProGuard does a great job of optimizing these hierarchies anyway. The real cost is in developer time saved by catching state-related bugs at compile time.