![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements