Can this be null in Scala?

醉酒当歌 提交于 2019-12-07 01:18:10

问题


I just read this question and stumbled upon the following quote:

Scala treats == as if it were defined as follows in class Any:

final def == (that: Any): Boolean = 
  if (null eq this) (null eq that) else (this equals that)

The (null eq this) part made me wonder: Is it actually possible to call methods on null pointers? Can this be null in Scala?


回答1:


Check out the Scala language specification, namely 6.3 The Null Value chapter:

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 class scala.AnyRef as follows:

eq(x) and ==(x) return true if the argument x is also the “null” object.

ne(x) and !=(x) return true if the argument x is not also the “null” object.

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.

Of course at the implementation level it is optimized and ordinary null is used.




回答2:


null is the only instance of Null class and it's a valid object. Null is a subtype of all reference types.




回答3:


I'm pretty new to Scala, but the only way I see that as being possible is due to the fact that "null" itself is an instance of Null, and not exactly a special value like "null" in Java.

http://blog.sanaulla.info/2009/07/12/nothingness/

This article helped me understand this a bit better.



来源:https://stackoverflow.com/questions/10072645/can-this-be-null-in-scala

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