Krešimir Nesek
Krešimir Nesek

Reputation: 5512

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?

Upvotes: 4

Views: 1600

Answers (2)

Dave Ford
Dave Ford

Reputation: 1973

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

Upvotes: 1

hotkey
hotkey

Reputation: 148169

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.

Upvotes: 11

Related Questions