Baeldung Pro – Kotlin – NPI EA (cat = Baeldung on Kotlin)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.