Description
Currently, our format API can be used in two ways: with explicit serializer, and with inferred from the type parameters, for exaple:
// Explicit
val jsonString = Json.decodeToString(MyClass.serializer(), MyClass(...))
val data = Json.encodeFromString(MyClass.serializer(), jsonString)
// Implicit
val jsonString = Json.decodeToString(MyClass(...)) // Inferred type-parameter T
val data = Json.encodeFromString<MyClass>(jsonString) // Or data: MyClass = Json.encodeFromString(sonString)
We always promote usages of the latter, because it has the same meaning, but in the meantime is more expressive and concise. It is based on the experimental typeOf
function and we are able to retrieve the serializer using KType
.
Unfortunately, it has two downsides:
- To retrieve the serializer, we have to use reflection. It prevents usage of this API with Graal (Kotlinx Serialization with GraalVM Native Images #1125) and also complicates Android usages
- Serializer retrieval is slow and often slower than the serialization itself. The recommended and concise API shouldn't behave this way.
Proposal
Introduce the notion of intrinsic to the serialization plugin. serializer()
and serializerOfNull
are going to be evaluated in the compile-time. Additionally, this evaluation will happen transitively through all reified inline
functions that leverage serializer<T>
.
To properly resolve context-specific serializers, more compact contextualOrDefault(defaultSerializer)
function will be used instead.