Is something like this possible with serialization...
# serialization
j
Is something like this possible with serialization? I'm just going to post the sample code here because it's quite a bit to explain. My goal is to ensure that any
Child2
instances inside of
Child1
instances are always
===
. In some manner, I sort of want to deserialize all the
Child2
instances and use their references as the deserialized input for the
Child1
instances, and throw an exception if the serialized data doesn't conform.
Copy code
fun main() {
    val test = Root()
    
    val child2 = Child2("Foo")
    val Child1 = Child1("Bar", child2)

    root.children1.add(child1)
    root.children2.add(children2)
    
    val jsonOutput = Json.encodeToString(test)
    
    val testInput = Json.decodeFromString<Root>(jsonOutput)
    
    /* Is it possible to make this true after deserialization? */
    testInput.children1.first().bar === testInput.children2.first()
}

@Serializable
class Root {
    val children1 = mutableListOf<Child1>()
    val children2 = mutableListOf<Child2>()
}

@Serializable
class Child1(
    val foo: String,
    val bar: Child2,
)

@Serializable
class Child2(val value: String)
My current workaround is to just make
Child1
store a string reference to `Child2`'s value and look up the instance at runtime.
g
Did you try to use
value class
for your Child2? I'd guess the === is forwarded to the String class, and as the JVM uses a String Constant Pool to not duplicate strings, it may work. But I won't feel very confident about it to be honest.
It's likely doable with a custom serializer if you have a pool of Child2 defined inside, which could create mem leaks tho. (If it was my project, I'd challenge the use of '===' to start with.)