I am trying to assign null to a variable which is Double like this:
var foo = 0.0
foo = null
However, this gives an error that null cannot be implicitly converted to Double
So I do this instead:
foo = null.asInstanceOf[Double]
however the new value for foo is 0.0
How can I set the value to null?
You can't. Double is a value type, and you can only assign null to reference types. Instead, the Scala compiler replaces null with a default value of 0.0.
In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.
Integer , which is a subtype of java. lang. Object (a.k.a. scala. AnyRef ): it's a reference type, so you can use null .
Null is the type of the null literal. It is a subtype of every type except those of value classes. Value classes are subclasses of AnyVal, which includes primitive types such as Int, Boolean, and user-defined value classes. Since Null is not a subtype of value types, null is not a member of any such type.
You can't. Double
is a value type, and you can only assign null
to reference types. Instead, the Scala compiler replaces null
with a default value of 0.0.
See default values in the SLS 4.2:
default type
0 Int or one of its subrange types
0L Long
0.0f Float
0.0d Double
false Boolean
You cannot assign Java primitives to null
, either. And while Scala's Double
isn't truly a primitive (it is actually a class in Scala), it needs to compile down to double
in Java byte code. Instead, you should use Option[Double]
if you want to represent a value that is missing entirely, and try to never use null
in Scala.
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