Sobes.tech
Junior — Middle

Is it possible in Kotlin to create a class marked as sealed that will inherit from another sealed class?

sobes.tech AI

Answer from AI

In Kotlin, a class marked as sealed can inherit from another sealed class. The subclass can also be sealed, allowing the creation of hierarchies with a limited set of subclasses at multiple levels. The main condition is that all subclasses of a sealed class must be in the same file as the sealed class itself.

Example:

sealed class Animal {
    sealed class Mammal : Animal() {
        class Dog : Mammal()
        class Cat : Mammal()
    }
    class Bird : Animal()
}

Here, Mammal is a sealed class inheriting from the sealed class Animal. This approach allows creating more complex hierarchies with a controlled set of subclasses.