Is there way to create a serializer for sealed cla...
# serialization
j
Is there way to create a serializer for sealed class that could be two types? I've got it working except for the descriptor, which I can either leave as an empty class descriptor and it still work or use
buildSerialDescriptor
but that is marked as internal and experimental. The class is just like this:
Copy code
public sealed class Union2<out T1T, out T2T> {
    data class T1<T1T>(val value: T1T): Union2<T1T, Nothing>()
    data class T2<T2T>(val value: T2T): Union2<Nothing, T2T>()
}
b
I think using it should be fine for now. There's an issue recognizing that there isn't a better way at the moment: https://github.com/Kotlin/kotlinx.serialization/issues/1775 You just need to be careful it's used correctly, since it's unsafe/unchecked (like its documentation mentions).
e
are you looking to do an untagged union like this?
Copy code
class Union2Serializer<T1, T2>(
    private val t1Serializer: KSerializer<T1>,
    private val t2Serializer: KSerializer<T2>,
) : KSerializer<Union2<T1, T2>> {
    override val descriptor: SerialDescriptor = SerialDescriptor(
        "Union2<${t1Serializer.descriptor.serialName}, ${t2Serializer.descriptor.serialName}>",
        JsonElement.serializer().descriptor,
    )

    override fun serialize(encoder: Encoder, value: Union2<T1, T2>) = when (value) {
        is Union2.T1 -> encoder.encodeSerializableValue(t1Serializer, value.value)
        is Union2.T2 -> encoder.encodeSerializableValue(t2Serializer, value.value)
    }

    override fun deserialize(decoder: Decoder): Union2<T1, T2> {
        val json = (decoder as JsonDecoder).decodeJsonElement()
        return try {
            Union2.T1(decoder.json.decodeFromJsonElement(t1Serializer, json))
        } catch (_: SerializationException) {
            Union2.T2(decoder.json.decodeFromJsonElement(t2Serializer, json))
        }
    }
}
I think wrapping
JsonElement.serializer().descriptor
would be the most appropriate thing in that case
j
Yep exactly that thanks! I'm curious why JsonElement is the most appropriate?
e
because that's what that serializer actually does - no knowledge about the structure at all