Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a runtime class of a variable in Kotlin?

I want to get a reference to a runtime KClass of a variable. I went through documentation on classes and reflection, but the documentation seems to only explain how to get a static reference to KClass (e.g. String::class for String)

I need a runtime KClass of a variable. This doesn't seem to compile:

fun test(x: Any) {
    val klazz = x::class
} 

How does one get the KClass of x in the example above?

like image 757
Krešimir Nesek Avatar asked Dec 15 '22 08:12

Krešimir Nesek


2 Answers

As said in the reference, you can use .javaClass.kotlin to get KClass token of an object. Example:

fun printKClass(x: Any) {
    val c = x.javaClass.kotlin
    println(c)
}

For any further manipulations with the KClass, you should also add kotlin-reflect library as a dependency, since the reflection functionality has been moved out of kotlin-stdlib.

like image 80
hotkey Avatar answered Jan 08 '23 01:01

hotkey


x::class works fine as long you have kotlin-reflect in your classpath.

like image 39
Dave Ford Avatar answered Jan 07 '23 23:01

Dave Ford