11

Possible Duplicate:
If an Int can't be null, what does null.asInstanceOf[Int] mean?

I tried the following in REPL:

scala> null.asInstanceOf[Int]
res12: Int = 0

scala> null.asInstanceOf[Float]
res13: Float = 0.0

scala> null.asInstanceOf[Double]
res14: Double = 0.0

It would expect a runtime exception (NPE or ClassCastException) in that case.
Could anybody explain why Scala casts null to zero?

Community
  • 1
  • 1
Michael
  • 10,185
  • 12
  • 59
  • 110

3 Answers3

6

It's really strange, as it is not the behaviour expected according to the specification:

asInstanceOf[T] returns the null object itself if T conforms to scala.AnyRef, and throws a NullPointerException otherwise.

-- The Scala Language Specification, Version 2.9, p. 75.

And it's a known bug that is closed but related to this one, which is open.

Nicolas
  • 24,509
  • 5
  • 60
  • 66
3

The reason is that null is a reference type - casting always converts to another reference type - in this case the boxed version of Int or Double.

In the next step, the compiler converts the boxed object to a primitive value. If the boxed Int object is null, its corresponding default primitive value is 0.

See: If an Int can't be null, what does null.asInstanceOf[Int] mean?

Community
  • 1
  • 1
axel22
  • 32,045
  • 9
  • 125
  • 137
1

Those types all extend AnyVal, for which a value cannot be null by assignment, the reason why it turns them into zero in response to asInstanceOf however escapes me. It appears to only be doing this in the REPL however which is a slightly special case. In real code it returns null.

Sean Parsons
  • 2,832
  • 21
  • 17
  • I did not try it in "real" code by myself but this is the behaviour my colleague noticed in "real" code. – Michael Jul 05 '12 at 06:54