Sobes.tech
Junior — Middle

Kuidas rakendada pärandamist klassist, mis on märgitud kui sealed?

sobes.tech AI

Vastus AI-lt

In Kotlin, a class declared as sealed restricts inheritance to only 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 in another file, it cannot be inherited from.

Therefore, to implement inheritance from a sealed class:

  • You must be in the same file where the sealed class is declared.
  • Declare subclasses within that file.

Example:

sealed class Result

class Success(val data: String) : Result()
class Error(val error: Throwable) : Result()

If extensibility outside the file is required, sealed is not suitable; you should use a regular open class or interface instead.