- Trending Categories
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
- Related Articles
- Kotlin equivalent of Java's equalsIgnoreCase
- Swift "if let" statement equivalent in Kotlin
- What is the equivalent of Java static methods in Kotlin?
- What is the equivalent of Java static final fields in Kotlin?
- What's the Kotlin equivalent of Java's String[]?
- When can we use the getClass() method in Java?
- Equivalent for Row_Number() in SAP ABAP
- ROW_NUMBER() equivalent in MySQL for inserting?
- MySQL LIMIT clause equivalent for SQL SERVER?
- What is the equivalent of sumproduct function of Excel for two vectors in R?
- Creating POJO Class for Kotlin
- Override getter for Kotlin data class
- MongoDB equivalent of WHERE IN(1,2,…)?
- C++ equivalent of instanceof
- Number of Equivalent Domino Pairs in Python

Advertisements