Since Int "does not conform to" AnyRef, I am not sure why it doesn't throw a NullPointerException according to Scala Reference on Section 6.3 :
asInstanceOf[T ] returns the “null” object itself if T conforms to scala.AnyRef, and throws a NullPointerException otherwise
And neither does null.asInstanceOf[Double]
, null.asInstanceOf[Boolean]
, null.asInstanceOf[Char]
.
PS: My scala library is of version 2.9.0.1 and OS windows XP
Indeed it is a bit surprising given the section 6.3 of the language spec as indicated in the ticket by huynhjl.
The behaviour (
null.asInstanceOf[Int]
gives you0
) on the other hand is somewhat consistent with the following observation:And as such may be useful in a generic class when you want to have 'a value' for type
X
, even if you don't have a particular value available. As in the second observation:In Scala
Null
is a type, which has a single valuenull
. Sincenull
is a value and every value in Scala is an object, you can call methods on it.