cosmosa
cosmosa

Reputation: 761

scala: assign null to primitive

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?

Upvotes: 7

Views: 17096

Answers (4)

B Custer
B Custer

Reputation: 241

An alternative (perhaps easiest) approach is just to use java.lang.Double instead of scala.Double, and assign to java.lang.Double.NaN instead of null.

Then you can just do

if(foo.isNaN) { work around not a number case } else { usual case }

when using the variable.

I say this is perhaps easiest because if your intention is to be able to check for Not-Available (or non-existing) status of a Double value, while otherwise using the variable(s) with usual Double arithmetic & operators, then using the java float primitives is quite a bit simpler than aliasing and otherwise working around the wrapper class of Option[Double].

See: Option[Double] arithmetic operators and Can float (or double) be set to NaN?

Upvotes: 3

Binzi Cao
Binzi Cao

Reputation: 1085

To answer your question why the complier complain when assigning a null to double variable, you can easily understand via the scala classes hierarchy diagram:

http://docs.scala-lang.org/tutorials/tour/unified-types.html

enter image description here

In short,

  • Double is a sub class of Anyval
  • null (a instance of Null) is a sub class of AnyRef.

So they are different types or classes in scala, it is similar to assign a List to a String.

Upvotes: 1

mavarazy
mavarazy

Reputation: 7735

You should never use null in Scala, instead take a look at Option, Option[Double] specifically

val foo = Some(0.0)
foo = Option.empty[Double]

Even Java introduced it's Optional values, instead of null.

https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html http://www.scala-lang.org/api/2.7.4/scala/Option.html

Upvotes: 0

Michael Zajac
Michael Zajac

Reputation: 55569

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.

Upvotes: 15

Related Questions