Intrinsics for serializer() function
See original GitHub issueCurrently, 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 (https://github.com/Kotlin/kotlinx.serialization/issues/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.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:36
- Comments:8 (3 by maintainers)
Top GitHub Comments
@snowe2010 The work has to be done in the compiler plugin — currently, they can’t provide intrinsics, and we have to change that. I’m working at this task at the moment, and I hope I will be able to present results soon
It’s already implemented in the not-yet-released Kotlin 1.8.0, stay tuned!