Nurseyit Tursunkulov
Nurseyit Tursunkulov

Reputation: 9400

Kotlin sealed class when expression not working in compose

I have following code:

sealed class ChooseCarState {
 data class ShowCarsState(val car: Int) : ChooseCarState()
 object ShowLoadingState : ChooseCarState()
 data class ShowError(val message: String) : ChooseCarState()
}

when observe this sealed class from ViewModel in composable function:

@Composable
fun showCars(){
val state = viewModel.chooseCarState.collectAsState()
when(state.value){
    is ChooseCarState.ShowCarsState->{
        val car = (state.value as ChooseCarState.ShowCarsState).car
    }
    is ChooseCarState.ShowLoadingState->{

    }
    is ChooseCarState.ShowError ->{
        val message  = (state.value as ChooseCarState.ShowError).message
    }
  }
}

I got ClassCastException, in spite of the fact that I am casting in is statement.

What could be a problem?

Upvotes: 0

Views: 1655

Answers (1)

Adrian K
Adrian K

Reputation: 4863

The problem is that from the compiler's point of view, there is no guarantee that state.value will always return the same value, since it is not a final field. You can solve this by assigning state.value to a variable which you can then safely cast. is then available for smart casts.

@Composable
fun showCars(){
val state = viewModel.chooseCarState.collectAsState()
when(val currentState = state.value){
    is ChooseCarState.ShowCarsState->{
        val car = currentState.car
    }
    is ChooseCarState.ShowLoadingState->{

    }
    is ChooseCarState.ShowError ->{
        val message  = currentState.message
    }
  }
}

Upvotes: 4

Related Questions