Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getting class in Kotlin using double-colon (::)?

We know that double-colon (::) is used to get function (callable) reference in Kotlin, e.g. String::compareTo, "string"::compareTo.

In Java we use SomeClass.class and someInstance.getClass() to get the class. Why in Kotlin we use SomeClass::class and someInstance::class while class is not a function/method?

println(String::compareTo) // output: fun kotlin.String.compareTo(kotlin.String): kotlin.Int println("string".compareTo("strong")) // output: -6 println(String::class) // output: class kotlin.String println("string".class) // compile error 
like image 732
fikr4n Avatar asked Jul 26 '17 23:07

fikr4n


People also ask

What is the use of double colon in Kotlin?

Kotlin double colon operator The double colon operator (::) is used to create a class or a function reference. In the code example, we create a reference to a class and to a function with the double colon operator. With the double colon operator, we refer to the String class. We print all its ancestors.

What does :: class Java do Kotlin?

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.

What is double exclamation in Kotlin?

In Kotlin, "!!" is an operator that is known as the double-bang operator. This operator is also known as "not-null assertion operator". This operator is used to convert any value to a non-NULL type value and it throws an exception if the corresponding value is NULL.

What does :: in Java mean?

The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions.


2 Answers

In Kotlin you can write Object::class, which will give you a KClass. KClass is not equivalent to the class Class that we know from Java. If you want to get the Java Class class you can write Object::class.java - i.e.: println("string"::class.java)

Also in java, .class is not a method or a member - it is a special directive for the compiler to access the class. I guess each language select the syntax that makes most sense for it, and kotlin's creators decided to use ::

like image 151
Lior Bar-On Avatar answered Sep 20 '22 16:09

Lior Bar-On


:: in Kotlin is about meta-programming, including method references, property references and class literals. See discussion about class literals.

like image 23
Miha_x64 Avatar answered Sep 20 '22 16:09

Miha_x64