看起来编译器不想在putSerializable
and中使用 Kotlinx 序列化类getSerializable
。它说Type mismatch: inferred type is MyViewModel.SavedState but Serializable? was expected
。
在我的活动中:
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.my_activity_layout)
viewModel.init(savedInstanceState?.getSerializable(SAVE_STATE) as? SavedState) // compiler complains here
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putSerializable(SAVE_STATE, viewModel.buildSaveState()) // and here
}
在我的视图模型中:
fun buildSaveState(): SavedState =
SavedState(value1, value2, value3, value4)
@Serializable
data class SavedState(val foo: Boolean?,
val foo1: Enum1?,
val foo2: Enum2?,
val foo3: MyType?)
我的风格:
@Serializable
sealed class MyType {
data class MyType1(val foo4: Enum3) : MyType()
data class MyType2(val foo5: Enum4) : MyType()
enum class Enum3 {
...
}
enum class Enum4 {
...
}
}