Moti Bartov
Moti Bartov

Reputation: 3592

Android studio wont suggest add remaining branches in `when` statement

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 enter image description here

But on other project it wont, and only suggest to add else branch like this, can you guess why? enter image description here

Upvotes: 2

Views: 38

Answers (2)

Moti Bartov
Moti Bartov

Reputation: 3592

I've found the problem!

The problem was an incorrect package name in the sealed class file! Like this: enter image description here

Once I've fixed to the correct package the problem was gone.

Upvotes: 0

tyg
tyg

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

Related Questions