Sobes.tech
Junior — Middle

How to determine the parameter type in Kotlin for a generic type without using reified?

sobes.tech AI

Answer from AI

In Kotlin, without using reified, you cannot directly obtain the type of a generic parameter due to type erasure. However, you can explicitly pass the class type through a parameter like Class<T> or KClass<T> to determine the type at runtime.

Example:

fun <T> printType(clazz: Class<T>) {
    println("Type is: ${clazz.simpleName}")
}

printType(String::class.java)  // Will output: Type is: String

If the function is generic and not inline, then to determine the type of the parameter, you need to explicitly pass the class type, since reified is only available for inline functions.

Thus, without reified, the type is passed explicitly, and you can determine the parameter's type based on it.