Sobes.tech
Junior — Middle

How can the type of a generic parameter be determined at runtime without using reified?

sobes.tech AI

Answer from AI

In Kotlin, without using reified types, it is not possible to directly determine the type of a generic parameter at runtime due to type erasure. However, you can explicitly pass the class type as a parameter to a function or constructor:

fun <T> doSomething(clazz: Class<T>) {
    // Use clazz to determine the type T at runtime
    println("Type of T: ${clazz.simpleName}")
}

doSomething(String::class.java) // Will print: Type of T: String

Thus, the type is explicitly passed, and you can work with it at runtime without reified. This is a common pattern to work around the type erasure limitation.