The code below prints “Default”, not “abc” as I expected. Apparently the init block runs after deserialization, and wipes out whatever was set by the deserializer. I thought init blocks ran as part of the primary constructor, which would run before anything else could touch the object. Is that not so?
@Serializable
class Foo {
var name: String
init {
name = "Default"
}
}
fun main() {
val foo = Foo()
foo.name = "abc"
val json = Json.stringify(Foo.serializer(), foo)
val foo2 = Json.parse(Foo.serializer(), json)
println(json)
println(foo2.name)
}
Yes, that works, but my example code is a boiled down example from more complex code. I need a var due to other issues with the serialization library and class hierarchies (discussed in a recent post). I may be able to get rid of my init block, but I want to understand what’s going on. Is it the intent of the serialization library to behave like this, or a bug?