Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this be null in Scala?

Tags:

null

this

scala

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?

like image 293
fredoverflow Avatar asked Apr 09 '12 11:04

fredoverflow


3 Answers

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.

like image 125
Tomasz Nurkiewicz Avatar answered Oct 29 '22 18:10

Tomasz Nurkiewicz


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

like image 20
senia Avatar answered Oct 29 '22 19:10

senia


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.

like image 1
pcalcao Avatar answered Oct 29 '22 18:10

pcalcao