简体   繁体   English

Kotlin 密封 class 当表达式在 compose 中不起作用时

[英]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:当在可组合 function 中观察来自 ViewModel 的密封 class 时:

@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.我得到了 ClassCastException,尽管我在is语句中进行转换。

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.问题在于,从编译器的角度来看,无法保证state.value将始终返回相同的值,因为它不是最终字段。 You can solve this by assigning state.value to a variable which you can then safely cast.您可以通过将state.value分配给一个变量来解决此问题,然后您可以安全地对其进行转换。 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
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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