Vishrant
Vishrant

Reputation: 16668

Why in Scala this statement is not a NullPointerException? null.asInstanceOf[Double]

I am coming from Java, and trying to understand the following Scala syntax

null.asInstanceOf[Double]

Why is this not a NullPointerException?

I was trying to do something like:

var d : Double = 0
if(d == null)
    // do something

However, I got following error message:

comparing values of types Double and Null using `==' will always yield false

This got fixed when I changed null to null.asInstanceOf[Double] as per this answer, but this is a weird statement for me, how on earth this is working?

Upvotes: 1

Views: 124

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70287

Scala's scala.Double does not correspond to Java's java.lang.Double. Scala's double inherits from AnyVal, the parent of all value types. It most closely corresponds to the primitive type double in Java, which can't be null. When you do null.asInstanceOf[Double], you're actually getting the double value 0.0, not a null double.

From the Scala language specification section 6.3

[the null value] implements methods in scala.AnyRef as follows

...

  • asInstanceOf[T] returns the default value of type T

And the default value of Double is zero.

So, in short, your value can't possibly be null because it's like a Java primitive. So you don't need to do a null check in this case.

Upvotes: 4

Related Questions