Middle
What are 'sealed' classes in Kotlin and in which cases should they be used?
sobes.tech AI
Answer from AI
The sealed class is used to represent a restricted class hierarchy. All direct subclasses of a sealed class must be defined in the same file as the sealed class itself, or in the same modules (for Kotlin 1.5+). This allows the compiler to verify that all possible subtypes are handled in a when expression, making it exhaustive without the need for an else branch.
Key features:
- All direct subclasses must be local.
- The constructor of a
sealedclass isprivateby default. - A
sealedclass cannot be abstract. - It does not allow creating instances.
Use cases:
- Representing a limited set of states or results. For example,
Loading,Success(data),Error(message).sealed class Result<out T> { data class Success<T>(val data: T) : Result<T>() data class Error(val message: String) : Result<Nothing>() object Loading : Result<Nothing>() } - Handling outcome variants in a
whenexpression with guaranteed exhaustiveness.fun processResult(result: Result<String>) { when (result) { is Result.Success -> println("Data received: ${result.data}") is Result.Error -> println("Error: ${result.message}") Result.Loading -> println("Loading...") } // No need for an else branch, as the compiler knows all subtypes. } - Used as an equivalent to enums with the ability to encapsulate data in each variant.
Comparison with enum classes:
| Characteristic | enum class |
sealed class |
|---|---|---|
| Instances | Limited set of named constants | Limited set of types |
| Data in variants | No (only properties) | Yes (via subclasses) |
| Abstract members | No | Yes |
| Inheritance | No | Yes, but limited to the same file/module |