Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What could be a problem?

>Solution :

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
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading