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?
:: 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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With