kotlin - 做任何==对象

kotlin 中的如下代码:

Any().javaClass

具有 java.lang.Object 的值。这是否意味着 AnyObject 是同一个类?他们是什么关系?

最佳答案

没有。

来自 Kotlin docs (强调我的)

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

此外,从我们发现的映射类型部分:

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!

这表示在 runtime java.lang.Objectkotlin.Any! 被同等对待。但是 ! 也意味着该类型是一个平台类型,这意味着禁用空检查等。

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).

...

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:

https://stackoverflow.com/questions/38761021/

相关文章:

android - 如何在 Kotlin 中获取当前的本地日期和时间

android - 使用 Retrofit 方法更具表现力

android - 使用 Kotlin 关闭/隐藏 Android 软键盘

kotlin - 在 Kotlin 中复制 map 最聪明的方法是什么?

android - 从 Activity Kotlin 中获取额外的字符串

kotlin - 如何在 Kotlin 中定义非序数枚举?

android - Kotlin 错误 : Dagger does not support inje

kotlin - 如何在一行上声明多个属性

android - 使用 Kotlin 组合整数标志的最佳方法?

kotlin - 为什么这个 Kotlin 方法有封闭的反引号?