Why is an array of arrays null?

Unitis indicated by a subtype 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 mistake / omission in the REPL array printing mechanism or is there a reason for this?

+3
source share
3 answers

It has been fixed for Scala 2.9 and now prints:

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

I think this is a problem / limitation with array initialization. For primitive values, arrays are initialized to the default value, which I assume the JVM by virtue of Scala arrays using their own arrays.

For other types, the value will be wrapped in an object, it seems that they are initialized as null.

, val units = Array.fill(5)(()).

+3

Zero, presumably, should only be displayed in this lowercase representation. As soon as you get the value from the array, it is "unpacked" into 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 such a discussion with Nothinginstead Unit.

+3
source

All Articles