开发者

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

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? Doubl开发者_Python百科e could theoretically also be initialized with null (although, thinking about it, as a language designer I'd rather not make that kind of change :-).


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜