Junior — Middle
How to implement inheritance from a class declared as sealed?
sobes.tech AI
Answer from AI
In Kotlin, a class declared as sealed restricts inheritance to within the same file where it is declared. This means that inheriting from a sealed class is only possible in the same file where it is defined.
If a class is declared as sealed and is located in a different file, it cannot be inherited from.
Therefore, to implement inheritance from a sealed class, you need to:
- Be in the same file where the sealed class is declared.
- Declare subclasses within this file.
Example:
sealed class Result
class Success(val data: String) : Result()
class Error(val error: Throwable) : Result()
If extendability outside the file is required, sealed class is not suitable; you should use a regular open class or interface.