Junior — Middle
Millistel juhtudel ja kus saab deklareerida alamklasse, kui klass on märgitud kui sealed?
sobes.tech AI
Vastus AI-lt
In Kotlin, a sealed class restricts the inheritance hierarchy: all subclasses of this 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 it, 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
sealedclass is declared. - Inside the
sealedclass 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.