Software Development

Why should developers use Kotlin’s Sealed Classes instead of standard Enums?

JO Asked by Joseph King · 02-01-2025
0 upvotes 8,776 views 0 comments
The question

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

0
EL
Answered on 15-01-2025

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.

0
CH
Answered on 18-01-2025

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?

PA 22-01-2025

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.

0
JE
Answered on 28-01-2025

Sealed interfaces are also a thing now in newer Kotlin versions! They allow even more flexibility when you need to implement multiple restricted hierarchies.

EL 02-02-2025

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.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session