简体   繁体   English

为什么null.asInstanceOf [Int]不抛出NullPointerException?

[英]why doesn't null.asInstanceOf[Int] throw a NullPointerException?

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 : 由于Int“不符合” AnyRef,所以我不确定为什么根据6.3节中的Scala参考 ,它不会引发NullPointerException:

asInstanceOf[T ] returns the “null” object itself if T conforms to scala.AnyRef, and throws a NullPointerException otherwise 如果T符合scala.AnyRef,则asInstanceOf [T]返回“ null”对象本身,否则抛出NullPointerException

And neither does null.asInstanceOf[Double] , null.asInstanceOf[Boolean] , null.asInstanceOf[Char] . 而且null.asInstanceOf[Double]null.asInstanceOf[Boolean]null.asInstanceOf[Char]

PS: My scala library is of version 2.9.0.1 and OS windows XP PS:我的Scala库的版本为2.9.0.1,并且OS Windows XP

In Scala Null is a type, which has a single value null . 在Scala中, Null是一种类型,具有单个值null Since null is a value and every value in Scala is an object, you can call methods on it. 由于null是一个值,而Scala中的每个值都是一个对象,因此可以在其上调用方法。

Indeed it is a bit surprising given the section 6.3 of the language spec as indicated in the ticket by huynhjl. 实际上,考虑到票证中huynhjl指出的语言规范的 6.3节,这有点令人惊讶。

The behaviour ( null.asInstanceOf[Int] gives you 0 ) on the other hand is somewhat consistent with the following observation: null.asInstanceOf[Int] ,行为( null.asInstanceOf[Int]给您0 )与以下观察结果有些一致:

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. 因此,当您想要类型X “值”时,即使您没有可用的特定值,这在泛型类中也很有用。 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....)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM