Classes
Kotlin Sealed Classes
Sealed Classes
Kotlin sealed classes restrict inheritance for type safety.
What Are Sealed Classes?
Sealed classes in Kotlin are a special kind of class that allows us to restrict the inheritance hierarchy. They provide a way to represent a restricted class hierarchy, where a value can have one of the types from a limited set, but cannot have any other type. This makes sealed classes ideal for representing algebraic data types, a common pattern in functional programming.
Defining a Sealed Class
To define a sealed class, use the sealed
keyword before the class declaration. This keyword ensures that all subclasses of the sealed class are known at compile time. The subclasses must be defined in the same file as the sealed class itself, ensuring that the class hierarchy is tightly controlled.
Benefits of Using Sealed Classes
- Exhaustive when expressions: When using sealed classes in
when
expressions, Kotlin ensures that all possible cases are covered. This eliminates the need for anelse
branch and provides compile-time safety. - Type Safety: Since the compiler knows all possible subclasses, it can enforce type safety more effectively.
- Cleaner Code: By restricting inheritance, sealed classes lead to cleaner and more maintainable code.
Using Sealed Classes in a When Expression
Sealed classes are particularly useful in when
expressions, where the compiler can ensure that all possible subclasses are accounted for. Here's an example:
Limitations and Considerations
While sealed classes are powerful, they come with certain limitations:
- All subclasses must be defined in the same file, which can lead to larger files for complex hierarchies.
- Sealed classes are not open for extension outside their file, limiting flexibility in some cases.
Conclusion
Sealed classes in Kotlin offer a robust way to enforce type safety and ensure exhaustive condition handling in when
expressions. By restricting inheritance, they provide both clarity and safety, making them a valuable tool in any Kotlin developer's toolkit.
Classes
- Previous
- Abstract Classes
- Next
- Enums