Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: assign null to primitive

Tags:

scala

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?

like image 646
cosmosa Avatar asked Apr 02 '17 12:04

cosmosa


People also ask

How do I assign a null to a variable in Scala?

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.

How do you use null in Scala?

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.

Can integer be null Scala?

Integer , which is a subtype of java. lang. Object (a.k.a. scala. AnyRef ): it's a reference type, so you can use null .

Can Boolean be null in Scala?

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.


1 Answers

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.

like image 179
Michael Zajac Avatar answered Sep 26 '22 02:09

Michael Zajac