16

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

爱国者
  • 4,298
  • 9
  • 47
  • 66

2 Answers2

5

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.

agilesteel
  • 16,775
  • 6
  • 44
  • 55
  • 1
    I'm afraid I can't agree with you. As the scala reference says, A reference to any other member of the “null” object causes a NullPointerException to be thrown – 爱国者 Nov 27 '11 at 14:08
  • 3
    Well this is exactly what happens. `null.toString` for example throws a NullPointerException. Exceptions are thrown at runtime. You can't do this in Java, because `null` is a language keyword there, so it won't compile. – agilesteel Nov 27 '11 at 14:23
-1

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....)
0__
  • 66,707
  • 21
  • 171
  • 266