I'm working with multiplatform, and I'm trying to ...
# reflect
m
I'm working with multiplatform, and I'm trying to get the
KType
from a class. It seems like the
jvm
versions of Kotlin have the ability to get
KType
(createType or starProjectedType), but I'm trying to find a way to get the class using the
common
libs. Does anyone have any recommendations? Mostly I'm trying to get the
KType
of an object to generate a serializer, which requires a
KType
to generate :
Copy code
/**
 * Retrieves a serializer for the given type [T].
 * This method is a reified version of `serializer(KType)`.
 */
public inline fun <reified T> serializer(): KSerializer<T> {
    return serializer(typeOf<T>()).cast()
}

/**
 * Creates a serializer for the given [type].
 * [type] argument can be obtained with experimental [typeOf] method.
 */
@OptIn(ExperimentalSerializationApi::class)
public fun serializer(type: KType): KSerializer<Any?> {
    val result = EmptySerializersModule.serializerByKTypeImpl(type) ?: type.kclass().serializerNotRegistered()
    return result.nullable(type.isMarkedNullable)
}
👀 1