1

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?
Ilya Muradyan
  • 387
  • 2
  • 13
  • 2
    The official guide covers both supported means https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#introduction-to-serializers (the choice between them is mostly stylistic) while the docs for the corresponding experimental functions list their limitations https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx-serialization-core/kotlinx.serialization/serializer.html – Roman Elizarov Nov 11 '20 at 12:47

1 Answers1

0
val c = C()
val s1 = serializer(C::class.javaObjectType)

satisfy me

Thomas Liao
  • 215
  • 3
  • 12