Getting class in Kotlin
In this recipe, we will look into the ways by which we can get the class reference in Kotlin. Primarily, we will be working with reflection. Reflection is a library that provides the ability to inspect code at runtime instead of compile time. In Java, we can get a variable's class through getClass()
, like something.getClass()
. Let’s see how to resolve a variable’s class in Kotlin.
How to do it...
- Java’s equivalent of resolving a variable's name is with the
.getClass()
method, for example,something.getClass()
. In Kotlin, we can achieve the same thing withsomething.javaClass
. - To get a reference to the reflection class, we used to do
something.class
in Java, whose Kotlin equivalent issomething::class
. This returns aKClass
. The special features of thisKClass
is that it provides introspection capabilities quite similar to the abilities provided to Java’s reflection class. Note that the KClass is different from Java’sClass
object. If you want to obtain a JavaClass
object...