简体   繁体   中英

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?

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
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM