Or simply asked WHY ?
It simply does not seems logical ...

if ( null.asInstanceOf[String]  == null )  println 
("null.asIstanceOf[String] is null")

println ("BUT !!!")

if ( null.asInstanceOf[Double] == 0.0 ) println ( 
"null.AsInstanceOf[Double] is 0 !!" )
up vote 1 down vote accepted

This is actually explained explicitly in the Scala Language Specification. Please, have a look at Section 6.3 The Null value, which says this:

The null value is of type scala.Null, and thus conforms to 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:

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

The default value for any subtype of AnyRef is null, the default value for subtypes of AnyVal is type-specific, but usually some type-specific neutral value, such as 0 for Int, Long, etc., 0.0 for Float and Double, and false for Boolean.

A Double is a primitive type so cannot be null; quoting from the 2.13 Standard Library Reference:

Double, a 64-bit IEEE-754 floating point number (equivalent to Java's double primitive type)

A String on the other hand is of course a fully fledged object and so can be null.

As an aside, you probably shouldn't be using null in your Scala code anyway.

  • You probably shouldn't be using asInstanceOf either. – Karl Bielefeldt Aug 10 at 15:11
  • Double is not a "primitive type". There are no primitive types in Scala. Double is a subtype of AnyVal, and thus also called a value type. – Jörg W Mittag Aug 10 at 17:07

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.