What is Sealed Class in Kotlin: Definition and Usage
sealed class in Kotlin is a special kind of class that restricts which classes can inherit from it, allowing a fixed set of subclasses. It helps represent restricted class hierarchies and is useful for handling different types in a controlled way.How It Works
Think of a sealed class like a closed box that only certain trusted friends can open. In Kotlin, when you declare a class as sealed, you limit the subclasses that can extend it to only those defined within the same file. This means you know all possible types that can come from this class, making your code safer and easier to manage.
This is especially helpful when you want to represent a fixed set of options or states, like different types of responses or events. The compiler can check that you handle all cases, so you won't miss any subclass when using when expressions.
Example
This example shows a sealed class Result with two subclasses: Success and Error. We use a when expression to handle each case safely.
sealed class Result { class Success(val data: String) : Result() class Error(val message: String) : Result() } fun handleResult(result: Result) { when (result) { is Result.Success -> println("Data: ${result.data}") is Result.Error -> println("Error: ${result.message}") } } fun main() { val success = Result.Success("File loaded") val error = Result.Error("File not found") handleResult(success) handleResult(error) }
When to Use
Use sealed classes when you have a limited set of related types and want to enforce that no other types can be added outside your control. This is common in representing states, results, or events in your app.
For example, sealed classes are great for:
- Modeling success and error results from network calls.
- Representing different UI states like Loading, Content, and Error.
- Handling different types of user actions or commands.
This helps make your code more predictable and easier to maintain.
Key Points
- Sealed classes restrict subclassing to the same file.
- They enable exhaustive
whenexpressions without anelsebranch. - Useful for representing fixed sets of types or states.
- Improve code safety and readability.
Key Takeaways
when expressions.