Junior — Middle
How to determine the type of a generic parameter in Kotlin if reified cannot be used?
sobes.tech AI
Answer from AI
In Kotlin, without using reified types, information about the generic type parameter is erased at runtime (type erasure). To determine the type of the parameter, you can pass a KClass<T> or Class<T> object as an additional parameter to a function or constructor. For example:
fun <T> doSomething(clazz: KClass<T>) {
when (clazz) {
String::class -> println("This is a string")
Int::class -> println("This is an integer")
else -> println("Other type")
}
}
// Call
doSomething(String::class)
Thus, you explicitly pass the type information, which can be used inside the function. This is the standard way to work around the absence of reified in regular (non-inline) functions.