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

拈花ヽ惹草 提交于 2020-06-09 11:41:25

问题


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

回答1:


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




回答2:


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 ::



来源:https://stackoverflow.com/questions/45339034/why-getting-class-in-kotlin-using-double-colon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!