Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting null to Int and Double in Scala [duplicate]

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?

like image 774
Michael Avatar asked Jul 05 '12 06:07

Michael


People also ask

Can null be cast to int?

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.

Can double be null in Scala?

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.

What is asInstanceOf in Scala?

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.

How do you typecast in Scala?

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).


3 Answers

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.

like image 74
Nicolas Avatar answered Sep 20 '22 21:09

Nicolas


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?

like image 32
axel22 Avatar answered Sep 20 '22 21:09

axel22


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.

like image 30
Sean Parsons Avatar answered Sep 24 '22 21:09

Sean Parsons