Is there a better way to get the serializer for a ...
# serialization
r
Is there a better way to get the serializer for a generic type if it’s not reified but you have its class?
Copy code
class Generic<T : Any>(
    private val clazz: KClass<out T>,
) {

    init {
        require(clazz.hasAnnotation<Serializable>())
    }

    fun serialize(value: T): String {
        val type = clazz.createType()
        val serializer = Json.serializersModule.serializer(type)
        return Json.encodeToString(serializer, value)
    }

}
e
ideally you'd pass in the serializer at construction time,
Copy code
class Generic<T : Any>(
    private val clazz: KClass<T>,
    private val serializer: KSerializer<T>,
)