kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Provide an option for custom serializers to receive types instead of serializers

Open Gaming32 opened this issue 1 year ago • 2 comments

What is your use-case and why do you need this feature?

I have a situation where I need the type arguments of an object to construct my custom serializer, but those type arguments will not be serializable themselves.

Describe the solution you'd like

I would like the serializer constructor to be able to accept KClass or KType parameters in addition to KSerializer parameters.

For example, say I have a class (this is a toy example, my actual situation is a bit more complex):

@Serializable(MyDataSerializer::class)
data class MyData<K, V>(val key: String, val value: V) {
    fun uncheckedCast() = value as K
}

I would want to define a serializer for this class that takes in the K type parameter as a KClass or KType. Notice how I can still receive V as a KSerializer, however.

class MyDataSerializer<K, V>(
    private val kType: KClass<K>, 
    private val vSerializer: KSerializer<V>
) : KSerializer<MyData<K, V>> {
    override val descriptor = SerialDescriptor("MyData", vSerializer.descriptor)

    override fun serialize(encoder: Encoder, value: MyData<K, V>) =
        encoder.encodeSerializableValue(vSerializer, value.value)

    override fun deserialize(decoder: Decoder) =
        MyData(getKeyFromClass(kType), decoder.decodeSerializableValue(vSerializer))
}

This would potentially require more complexity in the compiler plugin (this is a compiler plugin feature request, primarily) to locate a constructor that takes in an appropriate number of parameters, and its descriptor (since it could now take any mix of parameter types, not just "LKSerializer;".repeat(argCount)).

Gaming32 avatar Mar 01 '24 00:03 Gaming32

Is it something like #2555 ?

xiaozhikang0916 avatar Mar 01 '24 08:03 xiaozhikang0916

That issue deals with polymorphic serialization, abstract classes, and type inference. This issue isn't about any of those.

Gaming32 avatar Mar 01 '24 12:03 Gaming32