Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: are the initial values in an Array[Double] safe to use?

Tags:

scala

When an Array[Double] containing all zeros is required, is it safe to use

    val allZeros = new Array[Double](10)
    val whatever = allZeros( 5 )     // guaranteed to be 0.0, not null?
    assert( whatever == 0.0 )        // succeeds

or should I stick to

    val allZeros = Array.fill[Double](10)( 0.0 )

I am aware that the first version works, but is this a guarantee the language makes, i.e. will it always be safe? Double could theoretically also be initialized with null (although, thinking about it, as a language designer I'd rather not make that kind of change :-).

like image 966
Gregor Scheidt Avatar asked Jul 07 '11 04:07

Gregor Scheidt


2 Answers

Double in Scala is not an object like java.lang.Double, but the primitive type double. Thus the default value is 0. You can use your first version, which is perfectly safe.

However, I tend to prefer the second version, because it introduce another level of safety: it is self documented.

like image 60
paradigmatic Avatar answered Oct 21 '22 09:10

paradigmatic


Yes, it's safe. This is actually a guarantee Java makes and it carries on to Scala.

like image 3
Alexey Romanov Avatar answered Oct 21 '22 09:10

Alexey Romanov