Android can't serialize Kotlin lambda

Viewed 1345

we can read lambda function are serialize by default (https://discuss.kotlinlang.org/t/are-closures-serializable/1620),
but I getting error:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.example.dialogfragment.Arguments)

my class Arguments:

class Arguments(val function: ()-> Unit) : Serializable

What is wrong with my lambda ?
(I got this error when Android need to kill my fragment because low of memory :) )

1 Answers

If you want to serialize or parcel something you need to ensure every field is serializable or parcelable. In your case you are trying to serialize val function: ()-> Unit which is not serializable. Unfortunately, you can't make function serializable. You should rethink this argument class and pass something different. Probably you can get some parameter which leads to making a decision and then invoking a function in your fragment.

Related