1

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?

Vishrant
  • 15,456
  • 11
  • 71
  • 120

1 Answers1

4

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.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116