Can I get the serializer for type `Entity<T>...
# serialization
v
Can I get the serializer for type
Entity<T>
? Assuming T is @Serializable, how do I write
Json.encodeToString(T.serializer(),entity)
? Ideally without reflection because presumably kotlinx.serialization does it without reflection?
a
I believe the intended method is by using SerializersModule, but
T
can’t be type-erased
Copy code
import kotlinx.serialization.KSerializer
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.serializer

val serializersModule = SerializersModule {  }

fun <T> failure() {
  // Cannot use 'T' as reified type parameter. Use a class instead.
  val serializer: KSerializer<T> = serializersModule.serializer<T>()
}

inline fun <reified T> reified() {
  val serializer: KSerializer<T> = serializersModule.serializer<T>()
}
v
These are big methods, I don't think inline is an option. I shall do more reading.
e
there is a non-inline
SerializersModule.serializer(KType)
function
to get a
KType
you can either use
typeOf<T>()
where
T
is not type-erased, or
T::class.createType()
where
T
is type-erased but you have access to
KClass<T>
, assuming it has no type parameters
v
I wonder how KTor handles it... Lots to learn! I'll be back...
Cannot use 'Nothing' as reified type parameter