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
In Scala Null
is a type, which has a single value null
. Since null
is a value and every value in Scala is an object, you can call methods on it.
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 you 0
) on the other hand is somewhat consistent with the following observation:
new Array[AnyRef](3) // -> Array(null, null, null)
new Array[Int ](3) // -> Array(0, 0, 0)
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:
class X[A] {
var value: A = _
}
new X[Int].value // -> 0 (even if X is not specialized in A, hmmm....)