
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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<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
Advertisements