Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some short-cut for delegating serializers #2795

Open
kunyavskiy opened this issue Aug 27, 2024 · 0 comments
Open

Add some short-cut for delegating serializers #2795

kunyavskiy opened this issue Aug 27, 2024 · 0 comments
Labels

Comments

@kunyavskiy
Copy link

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

Delegating serializers are common feature, but it's quite boilerplatish to use. Maybe we can implement some API, which would provide shorter syntax to create them.

Describe the solution you'd like

E.g. it can be a class you can extend, like.

abstract class DelegatingKSerializer<S, T> : KSerializer<T>(val delegate: KSerializer<S>) {
   override val descriptor get() = delegate.descriptor
   abstract fun serialize(value: T): S
   abstract fun deserialize(value: S): T
   override fun serialize(encoder: Encoder, value: T) =  encoder.encodeSerializableValue(delegateSerializer, serialize(value))
   override fun deserialize(decoder: Decoder): S = deserialize(decoder.decodeSerializableValue(delegateSerializer))
} 

Then example from tutorial would look like

class ColorIntArraySerializer : DelegatingKSerializer<Int, Color>(serializer()) {
    override fun serialize(value: Color) = intArrayOf(
            (value.rgb shr 16) and 0xFF,
            (value.rgb shr 8) and 0xFF,
            value.rgb and 0xFF
    )

    override fun deserialize(array: IntArray) = Color((array[0] shl 16) or (array[1] shl 8) or array[2])
}

which is significantly cleaner, than original one.

It would be also nice to avoid passing serializer() explicitly here, but I didn't come up how we can do this.

@Kotlin Kotlin deleted a comment Aug 27, 2024
@Kotlin Kotlin deleted a comment from YeGop0218 Aug 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant