Junior — Middle
Is it necessary to explicitly specify subclasses within a sealed class during declaration?
sobes.tech AI
Answer from AI
In Kotlin, when declaring a sealed class, it is not necessary to specify all subclasses within its definition. Subclasses of a sealed class must be declared either in the same file or as nested classes within the sealed class. The main restriction is that all subclasses must be known to the compiler at compile time and be in the same module.
For example:
sealed class Result
class Success(val data: String) : Result()
class Failure(val error: Throwable) : Result()
Here, Success and Failure are subclasses of the sealed class Result, declared in the same file but not inside the sealed class itself.
Thus, explicit declaration of subclasses inside the sealed class is not required, but they must be in the same file (or module) to ensure the hierarchy's completeness and closedness.