1. Overview

In Java, when we’re going to retrieve a Class<T> type token, we’ll use the getClass() method on objects. In this short tutorial, we’re going to see how to do this in Kotlin.

2. The getClass() Equivalent

As of Kotlin 1.1, we can use the class reference syntax to retrieve the KClass<T> token in Kotlin:

val aString = "42"
val stringType = String::class
assertEquals(stringType, aString::class)

As shown above, the “::” reference can be used on both class types and instances. Before Kotlin 1.1, we should the javaClass extension property:

val aString = "42"
val type = aString.javaClass.kotlin
assertEquals("String", type.simpleName)

3. Conclusion

In this tutorial, we learned how to retrieve the KClass<T> token in Kotlin.

As usual, all the examples are available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.