Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton serialization in Kotlin

I'm wondering if it's possible in Kotlin to deserialize (restore property values) of a declared object, without having to manually assign the properties or resorting to reflection. The following snippet further explains:

object Foo: Serializable {
    var propOne: String = ""
    // ...

    fun persist() {
        serialize(this) 
        // no problem with serialization
    }

    fun restore(bytes: ByteArray) {

        val fooObj: Foo = deserialize(bytes) as Foo
        // It seems Kotlin allows us to use singleton as type!

        // obvioulsly either of the following is wrong:
        // this = fooObj
        // Foo = fooObj

        // ... is there a way to 'recover' the singleton (object) other than 
        //     manual assignment of properties (or reflection) ???    
    }
}
like image 376
Basel Shishani Avatar asked Oct 30 '22 06:10

Basel Shishani


1 Answers

There is no way to reassign the global reference to a singleton with a new instance. At most you can write out the properties during serialization, and then on deserialization directly read the properties and mutate the state in the original object. It will require custom code for you to assign the properties into the object either by direct assignment or reflection. It would be better if you make your own singleton mechanism that holds an instance that you can swap out to be another instance that you deserialize.

like image 173
Jayson Minard Avatar answered Nov 07 '22 23:11

Jayson Minard