
Sealed Class in Kotlin
📌 Sealed Class in Kotlin
A Sealed Class in Kotlin is a special type of class that is used to represent a restricted hierarchy of classes. It ensures that all subclasses are known and defined within the same file, providing better control over data modeling.
Sealed classes are often used when you have a fixed set of types that a variable can be, similar to Enums but more flexible.
✅ Key Features of Sealed Classes
Restricted Inheritance → All subclasses must be defined in the same file.
Improved Safety → Ensures exhaustive
when
statements, eliminating the need forelse
.Data Modeling → Great for representing state or result types.
Abstract by Default → Cannot be directly instantiated.
✅ Syntax of Sealed Class
sealedclassResult { dataclassSuccess(valdata: String) : Result() dataclassError(val message: String) : Result() object Loading : Result()}
sealed class Result
→ A sealed class calledResult
.data class
→ Represents different outcomes (Success
,Error
).object
→ Represents a singleton (Loading
).
✅ Using Sealed Classes with When
Sealed classes are commonly used with when
expressions for type-checking.
📌 Example:
fun(result: Result) { (result) { is Result.Success -> println("Success: ${result.data}") Result.Error -> println("Error: ${result.message}") Result.Loading -> println() }}
No
else
required → Thewhen
statement is exhaustive because all subclasses are covered.
✅ Why Use Sealed Classes?
State Management: Useful in state-driven applications like mobile apps.
Error Handling: Ideal for representing API responses (Success, Error, Loading).
Clean Code: Reduces the need for complex conditional statements.
✅ Comparison: Sealed Class vs Enum
Feature | Sealed Class | Enum Class |
---|---|---|
Flexibility | Can have multiple properties and methods | Limited to constant values only |
Subclassing | Supports data classes and objects | Does not support subclassing |
Data Modeling | Good for complex state management | Suitable for simple state management |
When Exhaustiveness | Ensures exhaustive when statements | Requires else statement sometimes |
✅ Conclusion
Use Sealed Classes when you have a finite set of subclasses representing various states.
It improves safety by ensuring all cases are handled.
Combine sealed classes with
when
statements for clean and maintainable code.