Hi, I am trying to understand why this 'when' expression is not exhaustive: ```sealed class Fruit { ...
j
Hi, I am trying to understand why this 'when' expression is not exhaustive:
Copy code
sealed class Fruit {
    object Apple : Fruit()
    object Orange : Fruit()
}

fun <T : Fruit> eat(fruit: T): Unit =
    // 'when' expression must be exhaustive, add necessary 'else' branch
    when (fruit) {
        is Fruit.Apple -> {}
        is Fruit.Orange -> {}
    }
This is just a contrived example, I know that I could simply inline 'T' with 'Fruit'. I am more interested to understand why Kotlin fails to see that the 'when' expression is exhaustive.
v
My guess would be not enough type inference super powers. You should report it if there is no issue for it yet, maybe it gets added in the future 🙂
j
The error also disappears when you make it
when(fruit as Fruit)
but then the compiler warns you 'No cast needed' 🙂
🤷‍♂️ 1
👀 1
j
@Vampire I haven't found any previous issues related to this problem, but I am not sure how I should even search for this 😃 @Joris PZ Interesting, I haven't though of that
v
Well, if in doubt, just open a new one. If it is a duplicate they will close it as duplicate and if you actually tried to search first, you don't need to have a bad conscience. 🙂
j
(I searched for
when generics
and got lucky 🙂 )
j
Nice, thanks for finding it 🙂
v
Not so easy to implement it seems, given the history of the issue
😢 1
t
Of course you're example is not the real use case and I don't know how that looks. This comment is not intended as an answer your question. But generally, if you're having a sealed class that is only extended by nested objects, why not just use an enum?
j
@Tobias Berger Yeah, perhaps I should have come up with a more meaningful example. One difference between enums and sealed classes that are only extended by objects is that these objects are not only values but also types. So, in the above example, I have introduced Fruit, Apple, and Orange types. With enum I would have introduced only type Fruit.
t
true, haven't thought of that. If you need different interfaces for your "Fruits", an enum won't do.