gpt4 book ai didi

android - 是否有可能用函数文字序列化 Kotlin Data 类?

转载 作者:行者123 更新时间:2023-12-01 11:15:12 26 4
gpt4 key购买 nike

我有以下设置:

Kotlin 数据类:

data class Error(val throwable: Throwable, val reloadAction: (() -> Unit)? = null) : Serializable

类的初始化:
val instance = Error(throwable,this::loadData)

其中 this 是来自 Android 架构组件的 ViewModel
当我将此数据类传递给 parcelable 时:
parcel.writeSerializable(instance as Serializable)

我得到以下异常:
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.mypackagename.Error)
at android.os.Parcel.writeSerializable(Parcel.java:1468)
at com.mypackagename.CustomView$Companion$SavedState.writeToParcel(CustomView.kt:177)
...
Caused by: java.io.NotSerializableException: com.mypackagename.ExampleViewModel

在这个问题中: Is there a way to pass a function reference between activities? 是以下答案:

It will actually be Serializable if it is a function reference (SomeClass::someFunction) or a lambda. But it might not be, if it is some custom implementation of the functional interface () -> Unit, so you should check that and handle the cases when it's not.



这是我的情况吗?或者当函数是不可序列化对象(ViewModel)的函数时,不能序列化数据类?还有其他可能性如何在数据类中将函数文字作为 Serializable 传递吗?

最佳答案

问题在于 View 模型:com.mypackagename.ExampleViewModel .这个类是不可序列化的。

如果您使用函数引用,则目标对象(在本例中为 View 模型)也必须是可序列化的。

关于android - 是否有可能用函数文字序列化 Kotlin Data 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52837966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com