I’m trying to define a type that derives from a sealed interface and also a regular interface. However, I’m unable to find a way of doing this without inadvertently defining a direct subclass of the sealed interface.
For example, suppose I have a Fruit
sealed interface:
sealed interface Fruit {
open class Apple : Fruit
open class Orange : Fruit
}
Now I want to have fruit with additional properties - say I’m implementing a fruit shop, and the shop’s fruit is branded:
interface Branded {
val brand: String
}
I can create objects that implement both interfaces:
val brandedApple = object : Fruit.Apple(), Branded {
override val brand = "FruitsRUs"
}
The problem is: what is the type of brandedApple
? If I don’t declare the type explicitly, the compiler knows brandedApple
is both a Fruit
and a Branded
, but AFAIK, Kotlin doesn’t have a way of declaring that a value has more than one type (Intellij’s “Specify type explicitly” intention only offers to declare it as a Fruit
).
My first thought was to declare an interface that derives from both parent interfaces:
interface BrandedFruit: Fruit, Branded
The issue with this is that BrandedFruit
is treated as a direct subclass of Fruit
, so now the compiler requires this kind of thing:
fun processFruit(fruit: Fruit) = when (fruit) {
is Fruit.Apple -> "I like crunchy apples"
is Fruit.Orange -> "Oranges are best as juice"
is BrandedFruit -> TODO()
}
How do I declare a type that extends both Fruit
and Branded
without that type being a direct subclass of Fruit
?