Kotlin: Equivalent of getClass() for KClass

Jire picture Jire · Sep 18, 2015 · Viewed 54.3k times · Source

In Java we can resolve a variable's class through getClass() like something.getClass(). In Kotlin I am aware of something.javaClass which is nice but I want to be able to get the KClass in a similar way. I've seen the Something::class syntax but this is not what I need. I need to get the KClass of a variable. Does such functionality exist?

Answer

Alexander Udalov picture Alexander Udalov · Sep 18, 2015

The easiest way to achieve this since Kotlin 1.1 is the class reference syntax:

something::class

If you use Kotlin 1.0, you can convert the obtained Java class to a KClass instance by calling the .kotlin extension property:

something.javaClass.kotlin