Avatar ·

How to get the class of a generic parameter in Kotlin? (reified, inline and TypeReference)

Hello everyone! I've been writing in Kotlin recently and encountered a problem that was easy to solve in Java but is causing me difficulties in Kotlin. I need to know inside a function what type parameter it was called with. For example, I have this code: ```kotlin fun processList(items: List) { // How do I know here that T is String, Int, or something else? // I want to print the type to the log println("Processing items of type: ${T::class}") // Error! } ``` In Java, I would use Class and pass it explicitly. But in Kotlin, I want to avoid this and make the API cleaner. I tried using T::class, but the compiler says: "Cannot use 'T' as reified type parameter. Use a class instead." I read about reified but didn't fully understand how it works. Plus, I need the function to be univer