Casting with zero in Int and Double in Scala

Possible duplicate:
If Int cannot be null, what does the value null.asInstanceOf [Int] mean?

In REPL, I tried the following:

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

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

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

In this case, a run-time exception was expected ( NPE or ClassCastException ).
Can anyone explain why Scala distinguishes null to zero?

+6
source share
3 answers

This is really strange, as this is not the behavior expected by specification:

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

- Scala Language Specification, version 2.9 , p. 75.

And this is a known mistake that is closed, but related to this , which is open.

+5
source

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

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

See: If Int cannot be null, what does the value null.asInstanceOf [Int] mean?

+3
source

All these types extend AnyVal, for which the value cannot be null for its intended purpose, the reason why it turns them to zero in response to asInstanceOf, however, eludes me. This seems to be done only in the REPL, but this is a bit of a special case. In real code, it returns null.

+1
source

Source: https://habr.com/ru/post/919722/


All Articles