Kotlin: Equivalent of getClass() for KClass

Kotlin Programming

Question or issue of Kotlin Programming:

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?

How to solve this issue?

Solution no. 1:

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

Solution no. 2:

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.getClass(): KClass {
    return javaClass.kotlin
}

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

Or, if you prefer a property:

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

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

Solution no. 3:

Here’s my solution

val TAG = javaClass.simpleName

With javaClass.simpleName you can obtain your class name. Also the above example is very useful for android developers to declare on top of the class as an instance variable for logging purposes.

Solution no. 4:

Here are different Implementations to get class names. You can utilize it as per your requirements.

import kotlin.reflect.KClass

val  T.kClassName: KClass
get() {
    return javaClass.kotlin
}

Here we can get the class name in kotlin

val  T.classNameKotlin: String?
get() {
    return javaClass.kotlin.simpleName
}

Here we can get the class name in kotlin

val  T.classNameJava: String
get() {
    return javaClass.simpleName
}

Here are the outputs to the following operations.

fun main(){

val userAge = 0

println(userAge.kClassName) 
Output: class java.lang.Integer (Kotlin reflection is not available)

println(userAge.classNameKotlin)
Output: Int

println(userAge.classNameJava)
Output: Integer
}

Hope this helps!