Authors Top

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

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.

Authors Bottom

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!