Hi everyone. I am trying to serialize a class wher...
# serialization
m
Hi everyone. I am trying to serialize a class where a part is implemented by another class using the delegation pattern. Minimal example:
Copy code
interface WithValue { val x: Int }

@Serializable
data class WithValueImpl(override val x: Int) : WithValue

@Serializable
data class MyClass(val y: Int) : WithValue by WithValueImpl(1)

fun main() {
    println(Json.encodeToString(MyClass(5)))
    // prints: {"y":5}
}
In the documentation, I have only found that delegated properties are transient, but nothing regarding delegated interfaces. The desired result would be, that MyClass is encoded as
{"y": 5, "x": 1}
. Do you have any pointers for me?
t
I did simluar w/ sealed classes (not interface) and it worked. What happens if you add @Serializable to the interface?
m
Then the compiler is angry at me:
Copy code
@Serializable annotation is ignored because it is impossible to serialize automatically interfaces or enums. Provide serializer manually via e.g. companion object
Ok, one hack could be:
Copy code
interface WithValue { val x: Int }

@Serializable
data class WithValueImpl(override val x: Int) : WithValue

@Serializable
data class MyClass(val y: Int, val impl: WithValueImpl = WithValueImpl(1)) : WithValue by impl
but now I have
.x
or
.impl.x
for accessing the same value, this does not look that beautiful
r
@Manuel Dossinger did you ever find a solution to this problem with serializing/deserializing with delegated properties?
i'm running into this myself, and can't find a clear answer