Equivalent of getClass() for KClass in Kotlin


In this article, we will take an example and demonstrate how we can obtain the class reference in Kotlin. Kotlin does not support fetching the class reference directly, but you can obtain the same reference via extension itself. In the following example, we will see how we can do it via Kotlin library functions.

Example – Class reference using KClass

In this example, we will get the reference of the class.

import kotlin.reflect.KClass

fun main(args : Array<String>) {
   // to get the reference of the class
   fun<T: Any> T.getClass(): KClass<T> {
      return javaClass.kotlin
   }

   val myVariable = "String"
   val myAnotherVariable = 1

   // As the variable is of String type,
   // it will give us java.lang.String
   println("Kotlin type: ${myVariable.getClass()}")

   // this is of type Int
   println("Kotlin type: ${myAnotherVariable.getClass().simpleName}")
}

Output

On execution, it will yield the following output −

Kotlin type: class kotlin.String
Kotlin type: Int

Updated on: 01-Mar-2022

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements