简体   繁体   中英

Is there a possibility to serialize Kotlin Data class with function literal?

I have following setup:

Kotlin data class:

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

Initialization of class:

val instance = Error(throwable,this::loadData)

Where this is ViewModel from Android Architecture components

When I'm passing this data class to parcelable:

parcel.writeSerializable(instance as Serializable)

I get following exception:

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

In this question: Is there a way to pass a function reference between activities? is following answer:

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.

Is this my case? Or data class cannot be serialized when function is function of non serializable object (ViewModel)? Are there any other possibilities how to pass function literal as Serializable inside data class?

The problem ist the view model: com.mypackagename.ExampleViewModel . This class is not serializable.

If you use a function reference, the target object - in this case the view model- must be serializable too.

I had similar issue, my problem was that I didn't expect a data class not to be Serializable by default. It is important not to forget to implement the Serializable interface.

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