Junior — Middle
In what cases and where can subclasses be declared if a class is marked as sealed?
sobes.tech AI
Answer from AI
In Kotlin, a class marked as sealed restricts the inheritance hierarchy: all subclasses of such a class must be declared in the same file as the sealed class itself. This allows the compiler to know the complete set of subclasses and use this, for example, in when expressions without needing to write an else branch.
That is, subclasses of a sealed class can be declared:
- In the same file where the sealed class is declared.
- Inside the sealed class itself (nested classes).
Example:
sealed class Result {
class Success(val data: String) : Result()
class Error(val error: Throwable) : Result()
}
Or
sealed class Result
class Success(val data: String) : Result()
class Error(val error: Throwable) : Result()
But all these subclasses must be in the same file as the sealed class. This restriction helps ensure type safety and completeness of checks.