这在 Scala 中可以为 null 吗? [英] Can this be null in Scala?
问题描述
我刚刚阅读了这个问题并偶然发现了以下引用:
I just read this question and stumbled upon the following quote:
Scala 将 ==
视为在 Any
类中定义如下:
Scala treats
==
as if it were defined as follows in classAny
:
final def == (that: Any): Boolean =
if (null eq this) (null eq that) else (this equals that)
(null eq this)
部分让我想知道:真的可以在空指针上调用方法吗?this
在 Scala 中可以是 null
吗?
The (null eq this)
part made me wonder: Is it actually possible to call methods on null pointers? Can this
be null
in Scala?
推荐答案
查看 Scala 语言规范,即6.3 空值章节:
空值属于 scala.Null
类型,因此与每个引用兼容类型.它表示引用一个特殊的null"对象的引用值.这个对象实现类 scala.AnyRef
中的方法如下:
The null value is of type
scala.Null
, and is thus compatible with every reference type. It denotes a reference value which refers to a special "null" object. This object implements methods in classscala.AnyRef
as follows:
• eq(x)
和 ==(x)
如果参数 x
也是空"对象,则返回 true.
• eq(x)
and ==(x)
return true if the argument x
is also the "null" object.
• ne(x)
和 !=(x)
如果参数 x
不是空"对象,则返回 true.
• ne(x)
and !=(x)
return true if the argument x
is not also the "null" object.
这意味着在语义上,当您将某些内容与 null
文字或 null
文字与您实际指代的特殊 scala.Null
类.将 null
文字视为该类的简写.
This means that semantically when you compare something with null
literal or null
literal with something you are actually referring to method of a special scala.Null
class. Treat null
literal as a shorthand for that class.
当然在实现层面它被优化并且普通 null
被使用.
Of course at the implementation level it is optimized and ordinary null
is used.
这篇关于这在 Scala 中可以为 null 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!