Sealed classes in Kotlin provide a powerful way to represent restricted class hierarchies. They are particularly useful when dealing with a finite set of subclasses.
A sealed class is a class that restricts the possibility of inheritance. All direct subclasses of a sealed class must be declared in the same file as the sealed class itself. This feature ensures that the compiler knows all possible subclasses at compile-time.
To declare a sealed class, use the sealed
keyword before the class
keyword:
sealed class Result
class Success(val data: String) : Result()
class Error(val message: String) : Result()
object Loading : Result()
In this example, Result
is a sealed class with three subclasses: Success
, Error
, and Loading
.
Sealed classes are often used in scenarios where you need to represent a limited set of possibilities, such as:
Here's an example demonstrating how to use a sealed class with a when
expression:
fun handleResult(result: Result) = when (result) {
is Success -> println("Success: ${result.data}")
is Error -> println("Error: ${result.message}")
is Loading -> println("Loading...")
}
val successResult = Success("Data loaded")
handleResult(successResult) // Output: Success: Data loaded
val errorResult = Error("Network error")
handleResult(errorResult) // Output: Error: Network error
handleResult(Loading) // Output: Loading...
In this example, the when
expression is exhaustive without needing an else
branch, as the compiler knows all possible subclasses of Result
.
when
expressionsSealed classes in Kotlin offer a robust way to model restricted hierarchies. They provide type safety, exhaustive checking, and improved code organization. By leveraging sealed classes, you can create more expressive and maintainable code, especially when dealing with finite sets of related types.