Reputation: 3592
In my project I am using sealed classes. when I try to check a sealed class in a when
statement, usually Android Studio suggest to add remaining branches so the when
statement will be exhaustive.
Consider this sealed class:
sealed class State{
object Init : State()
object Loading : State()
class Next(data: T) : State()
}
Now in a when
statement:
when(state){
}
in one project Android Studio suggest to add remaining branches
But on other project it wont, and only suggest to add else
branch like this, can you guess why?
Upvotes: 2
Views: 38
Reputation: 3592
I've found the problem!
The problem was an incorrect package name in the sealed class file!
Like this:
Once I've fixed to the correct package the problem was gone.
Upvotes: 0
Reputation: 14964
You forgot to inherit from State
.
When you declare the classes inside of State
that does not automatically make them descendents of State
, they do not share that type. So the when
only knows of the single sealed class State
, nothing else.
That changes when you explicitly let your classes inherit from State
:
sealed class State {
object Init : State()
object Loading : State()
class Next(data: T) : State()
}
Now the when
sees the actual implementations of State
and the IDE recommends the quick fix "Add remaining branches".
Upvotes: 1