mercredi 11 novembre 2020

Obtaining serializer for a class in kotlinx.serialization

Assume that C is a serializable class:

@Serializable
class C

I have at least four ways of obtaining serializer for this class.

  1. Companion(?) function. Actually IDEA doesn't let me to go to declaration, so I assume it's a kind of synthetic compiler-plugn-generated function.
val s = C.serializer()
  1. serializer() call with reified type argument:
val s = serializer<C>()
  1. KClass experimental extension:
val c = C()
val s1 = C::class.serializer()
val s2 = c::class.serializer()
  1. serializer() semi-experimental overload:
val c = C()
val s1 = serializer(C::class.createType())
val s2 = serializer(c::class.createType())

The last two ways seem to be more powerful: for example, I may use it for polymorphic serialization getting actual KClass for an instance of abstract type and choosing the correct serializer.

I have several questions:

  1. What ways of obtaining serializer by type actually exist and what ways are preferrable?
  2. As I understand, I may register several serializers for one class, so which one do I get in each of these cases?
  3. Assuming I've registered a custom serializer for a class using @Serializable(with=...), is it possible to obtain a standard serializer for it somehow?




Aucun commentaire:

Enregistrer un commentaire