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?
CodePudding user response:
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
}
}
}