Sobes.tech
Middle

What restrictions exist for sealed classes in Kotlin?

sobes.tech AI

Answer from AI

Sealed classes in Kotlin have the following restrictions:

  • All subclasses of a sealed class must be declared in the same file as the sealed class itself. This limits extensibility outside the file.
  • Sealed classes cannot be open for inheritance outside this file, ensuring control over the class hierarchy.
  • Sealed classes cannot be abstract, but can contain abstract methods.

Example:

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

Here, all subclasses of Result are declared in the same file, allowing the compiler to know all possible inheritance options.

What restrictions exist for sealed classes in Kotlin… - sobes.tech