Could this be null in Scala?

I just read this question and came across the following quote:

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

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

The (null eq this) made me wonder: is it really possible to call methods on null pointers? Could this be null in Scala?

+7
source share
3 answers

Check out the Scala language specification , namely: 6.3. Null Value Section:

The null value is of type scala.Null and, therefore, is compatible with all references of the type. It denotes a reference value that refers to the special null object. This object implements methods in the scala.AnyRef class as follows:

eq(x) and ==(x) returns true if x also a null object.

ne(x) and !=(x) returns true if x not a “null” object either.

This means that semantically, when you compare something with a null literal or null literal with something that you are actually referring to a method of the special class scala.Null , Treat the null literal as an abbreviation for this class.

Of course, at the implementation level it is optimized and uses regular null .

+8
source

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

+3
source

I am new to Scala, but the only way I can see that this is possible is because "null" itself is an instance of Null, and not a very special value like "null" in Java.

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

This article helped me understand this a little better.

+1
source

All Articles