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?
In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.
The reference types such as Objects, and Strings can be nulland the value types such as Int, Double, Long, etc, cannot be null, the null in Scala is analogous to the null in Java.
In Dynamic Programming Languages like Scala, it often becomes necessary to cast from type to another. Type Casting in Scala is done using the asInstanceOf[] method. Applications of asInstanceof method. This perspective is required in manifesting beans from an application context file.
In order to cast an Object (i.e, instance) from one type to another type, it is obligatory to use asInstanceOf method. This method is defined in Class Any which is the root of the scala class hierarchy (like Object class in Java).
It's really strange, as it is not the behaviour expected according to the specification:
asInstanceOf[T]returns thenullobject itself ifTconforms toscala.AnyRef, and throws aNullPointerExceptionotherwise.-- 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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With