是否有任何==对象 [英] does Any == Object
问题描述
kotlin中的以下代码:
The following code in kotlin:
Any().javaClass
具有java.lang.Object
的值.这是否意味着Any
和Object
是同一类?他们有什么关系?
Has value of java.lang.Object
. Does that mean Any
and Object
are the same class? What are their relations?
推荐答案
否.
从科林文档 (强调我的)
Kotlin中的所有类都有一个公共的超类
Any
,这是默认设置 没有声明超类的类的super:
All classes in Kotlin have a common superclass
Any
, that is a default super for a class with no supertypes declared:
class Example // Implicitly inherits from Any
Any
不是java.lang.Object
;特别是它没有任何
equals()
,hashCode()
和toString()
以外的成员.请
有关更多详细信息,请查阅Java互操作性部分.
Any
is not java.lang.Object
; in particular, it does not have any
members other than equals()
, hashCode()
and toString()
. Please
consult the Java interoperability section for more details.
此外,在有关映射类型的部分中,我们发现:
Further, from the section on mapped types we find:
Kotlin特别对待某些Java类型.此类类型不是从 Java是按原样"的,但是被映射到相应的Kotlin类型.映射 仅在编译时起作用,运行时表示保留 不变. Java的原始类型被映射到相应的Kotlin 类型(请记住平台类型):
Kotlin treats some Java types specially. Such types are not loaded from Java "as is", but are mapped to corresponding Kotlin types. The mapping only matters at compile time, the runtime representation remains unchanged. Java’s primitive types are mapped to corresponding Kotlin types (keeping platform types in mind):
...
java.lang.Object
kotlin.Any!
这表示在运行时中,java.lang.Object
和kotlin.Any!
被视为相同.但是!
还意味着该类型是平台类型,这与禁用null检查等有关.
This says that at runtime java.lang.Object
and kotlin.Any!
are treated the same. But the !
also means that the type is a platform type, which has implication with respect to disabling null checks etc.
Java中的任何引用都可能为null,这使得Kotlin的要求 对于来自Java的对象,严格的null安全性是不切实际的.种类 Java声明在Kotlin中被特殊对待并称为平台 类型.放宽此类检查的Null,以确保安全性 因为它们与Java中的相同(请参阅下文).
Any reference in Java may be null, which makes Kotlin’s requirements of strict null-safety impractical for objects coming from Java. Types of Java declarations are treated specially in Kotlin and called platform types. Null-checks are relaxed for such types, so that safety guarantees for them are the same as in Java (see more below).
...
当我们在平台类型的变量上调用方法时,Kotlin不会 在编译时发出可空性错误,但调用可能会在以下时间失败 由于存在空指针异常或Kotlin的断言而导致运行时 生成以防止null传播:
When we call methods on variables of platform types, Kotlin does not issue nullability errors at compile time, but the call may fail at runtime, because of a null-pointer exception or an assertion that Kotlin generates to prevent nulls from propagating:
这篇关于是否有任何==对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!