https://kotlinlang.org logo
Title
v

v79

01/21/2023, 8:37 PM
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

Adam S

01/21/2023, 8:42 PM
I believe the intended method is by using SerializersModule, but
T
can’t be type-erased
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

v79

01/21/2023, 8:46 PM
These are big methods, I don't think inline is an option. I shall do more reading.
e

ephemient

01/21/2023, 9:00 PM
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

v79

01/21/2023, 9:13 PM
I wonder how KTor handles it... Lots to learn! I'll be back...
Cannot use 'Nothing' as reified type parameter