Roman Levinzon
10/06/2023, 12:15 PM@Serializable
annotation, fx User.
2. you write Json.encodeToString(User())
and run the project
3. Compiler generates UserSerializer
4. Later the serializer()
function is called that obtains UserSerializer
using reified type.
Here is what I’m missing: serializer()
function is part of the library. It doesn’t know about any code generated by the compiler. So how would it be able to resolve generated code? In other worlds how this “generated” serialzer gets registered for future use?
The reason I’m asking is I’m trying to build a library that works kind of similar to the serialization plugin and it is hard to implement this step. I have KSP that does all steps from 1-3. But really confused about how step 4 would look like
Appreciate all the input!ephemient
10/06/2023, 3:08 PMserializer()
function?@Serialize class Foo
causes the compiler plugin to modify the class so that there is a Foo.Companion.serializer()
functionfun <reified T> serializer<T>()
function is sort of a mix.Companion.serializer()
function of the typeRoman Levinzon
10/06/2023, 3:16 PM/**
* Retrieves a serializer for the given type [T].
* This overload is a reified version of `serializer(KType)`.
*
* This overload works with full type information, including type arguments and nullability,
* and is a recommended way to retrieve a serializer.
* For example, `serializer<List<String?>>()` returns [KSerializer] that is able
* to serialize and deserialize list of nullable strings — i.e. `ListSerializer(String.serializer().nullable)`.
*
* Variance of [T]'s type arguments is not used by the serialization and is not taken into account.
* Star projections in [T]'s type arguments are prohibited.
*
* @throws SerializationException if serializer cannot be created (provided [T] or its type argument is not serializable).
* @throws IllegalArgumentException if any of [T]'s type arguments contains star projection
*/
public inline fun <reified T> serializer(): KSerializer<T> {
return serializer(typeOf<T>()).cast()
}
ephemient
10/06/2023, 3:18 PMFoo.serializer()
does not use reflection. serializer<Foo>()
may or may not, depending on compiler/plugin version and switchesRoman Levinzon
10/06/2023, 3:19 PMephemient
10/06/2023, 3:20 PMRoman Levinzon
10/06/2023, 3:20 PMmySerializer()
And I want to resolve UserSerializer
val serializer: UserSerializer = mySerializer<User>()
This will only be possible using reflection?UserSerializer
is generated during KSP processing