Why can an Array of Units hold null?

358 Views Asked by At

Unit is specified to be a subtype of AnyVal (and its only value is ()), so why is this possible:

scala> val units = new Array[Unit](5)
units: Array[Unit] = Array(null, null, null, null, null)

Is this just a bug/omission in the REPL's array printing mechanism or is there a reason for it?

3

There are 3 best solutions below

0
On BEST ANSWER

It was fixed for Scala 2.9 and now prints :

scala> val units = new Array[Unit](5)
units: Array[Unit] = Array((), (), (), (), ())
1
On

The null is, presumably, only supposed to appear in this string representation. As soon as you get a value out of the array, it is “unboxed” to Unit:

scala> val units = new Array[Unit](5)
units: Array[Unit] = Array(null, null, null, null, null)

scala> units(0)
// note: no result

Compare with:

scala> val refs = new Array[AnyRef](5)
refs: Array[AnyRef] = Array(null, null, null, null, null)

scala> refs(0)                        
res0: AnyRef = null // we do get the null here

There was a similar discussion in that question with Nothing instead of Unit.

0
On

I think this is an issue/limitation with array initialization. For primitive values arrays are initialized to their default value I presumed by the JVM by virtue of Scala arrays leveraging native arrays.

For other types, the value would be wrapped into an object, it seems they come initialized as null.

If you want an array of unit, you may need to call val units = Array.fill(5)(()).