Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 519
Jarda Havelik Avatar asked Jan 27 '23 07:01

Jarda Havelik


2 Answers

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.

like image 91
Rene Avatar answered Jan 31 '23 10:01

Rene


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.

like image 29
Vojtěch Avatar answered Jan 31 '23 09:01

Vojtěch