Reputation: 4016
Given a class
class Pizza(name: String?) : Serializable {
var name: String? by Delegates.observable(name, {_,_,_ -> })
}
Why is this not serializable? It crashes with
Caused by: java.io.NotSerializableException: com.xxx.xxx.Pizza$$special$$inlined$observable$1
Upvotes: 1
Views: 470
Reputation: 6419
The reason behind your issue is the delegates are stored as an array in a synthetic backing field which is neither marked as transient nor serialziable, so it prevents the serialization. However just marking the property with @Transient will probably ruin your serialized form. And may not work at all
Before JetBrains decide to make a final resolution to this issue, you should use writeReplace
and readResolve
to override the default serializing mechanism. I've provided a sample solution below:
class Pizza(name: String?) : Serializable {
@Transient var name: String? by Delegates.observable(name)
private fun writeReplace(stream: ObjectOutputStream): Object = SerialProxy(name)
private class SerialProxy(var name: String): Serializable {
private fun readResolve(): Object = Pizza(name)
}
}
readObject()/writeObject() doesn't work because you have no way to set the delegate after constructor is invoked without using reflection.
Upvotes: 2