Proposal: abstract class implementing sealed interface, relaxing the rules

You can use a “shadow twin” for Animal interface. This can be used if you don’t have access to the original module:

// module 1 unchanged from original post
sealed interface Animal {
    val name: String
}

// module 2
private interface AnimalShadow {
    val name: String
}

abstract class MyAnimal internal constructor() : AnimalShadow { ... }

data class MyCat(override val name: String) : MyAnimal(), Cat { ... }

data class MyDog(override val name: String) : MyAnimal(), Dog { ... }

The shadow twin (AnimalShadow) contains a subset of the content of the original sealed interface (Animal) – all parts that you need in your shared implementation (MyAnimal). (In this use-case AnimalShadow has all the content of Animal, because MyAnimal needs the name and Animal does not have any other content).

Note: I just came up with these names (“shadow twin”). I guess these are not commonly used.

1 Like