Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to check generic type in Kotlin?
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
Example
For this example, we will create a generic class of 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
Advertisements
