why doesn't null.asInstanceOf[Int] throw a Nul

2019-01-26 04:40发布

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

2条回答
仙女界的扛把子
2楼-- · 2019-01-26 05:17

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....)
查看更多
太酷不给撩
3楼-- · 2019-01-26 05:24

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.

查看更多
登录 后发表回答