Kotlin: Equivalent of getClass() for KClass

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

EDIT: See comments, below, and answer from Alexander, above. This advice was originally for Kotlin 1.0 and it seems is now obsolete.

Since the language doesn't support a direct way to get this yet, consider defining an extension method for now.

fun<T: Any> T.getClass(): KClass<T> {
    return javaClass.kotlin
}

val test = 0
println("Kotlin type: ${test.getClass()}")

Or, if you prefer a property:

val<T: Any> T.kClass: KClass<T>
    get() = javaClass.kotlin

val test = 0
println("Kotlin type: ${test.kClass}")

Tags:

Java

Class

Kotlin