How to check generic type in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

In this article, we will see how we can get the type of a class that is used in Kotlin. There are no direct ways to do this in Kotlin. In order to check the generic type, we need to create an instance of the generic class<T> and then we can compare the same with our class.

Example

For this example, we will create a generic class of type<T> and we will pass our variable inside this class in order to check its type.

class MyGenericClass<T : Any>(val myclass: Class<T>) {
   companion object {
      inline operator fun <reified T : Any>invoke() = MyGenericClass(T::class.java)
   }
   fun check(t: Any) {
      when {
         myclass.isAssignableFrom(t.javaClass) -> println(t.javaClass)
         else -> println(t.javaClass)
      }
   }
}
fun main(vararg args: String) {
   // it should return String
   MyGenericClass<String>().check("TutorialsPoint.com")
}

Output

On execution, it will produce the following output −

class java.lang.String
raja
Updated on 16-Mar-2022 13:16:35

Advertisements