Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ::class and ::class.java in Kotlin?

Tags:

kotlin

In Java, we write .class (for example: String.class) to get information about the given class. In Kotlin you can write ::class or ::class.java. What is the difference between them?

like image 201
Seydazimov Nurbol Avatar asked Jan 17 '20 05:01

Seydazimov Nurbol


People also ask

What is :: class in Kotlin?

:: is just a way to write a lambda expression basically we can use this to refer to a method i.e a member function or property for example class Person (val name: String, val age: Int) Now we can write this to access the person which has the maximium age.

What are the differences between Kotlin and Java?

Kotlin offers object-oriented and functional features to developers. In contrast, Java only offers object-oriented programming. Kotlin offers extension creation capabilities, whereas Java doesn't offer any extension function. Kotlin doesn't support implicit conversions; however, Java supports implicit conversions.


Video Answer


2 Answers

By using ::class, you get an instance of KClass. It is Kotlin Reflection API, that can handle Kotlin features like properties, data classes, etc.

By using ::class.java, you get an instance of Class. It is Java Reflection API, that interops with any Java reflection code, but can't work with some Kotlin features.

like image 58
ardenit Avatar answered Sep 22 '22 12:09

ardenit


According to the Kotlin documentation, when we create an object using any class type as below the reference type will be type of KClass.

val c = MyClass::class  // reference type of KClass 

Kotlin class reference is not the same as a Java class reference. To get a Java class reference, use the .java property on a KClass instance.

val c = MyClass::class.java  // reference type of Java 

You can refer the Kotlin documentation For further details. https://kotlinlang.org/docs/reference/reflection.html#class-references

like image 24
Geeganage Punsara Prathibha Avatar answered Sep 22 '22 12:09

Geeganage Punsara Prathibha