3

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?

razlebe
  • 7,134
  • 6
  • 42
  • 57
soc
  • 27,983
  • 20
  • 111
  • 215

3 Answers3

4

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.

Community
  • 1
  • 1
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • I'm not sure the Unit value gets unboxed: `(new Array[Unit](5))(0) == ()` returns `false`. And `(new Array[Unit](5))(0) == null` returns `true` and an interesting warning! `{val a = Array.fill(5)(()); a(0) == ()}` will return `true`. – huynhjl May 02 '11 at 20:27
3

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)(()).

huynhjl
  • 41,520
  • 14
  • 105
  • 158
1

It was fixed for Scala 2.9 and now prints :

scala> val units = new Array[Unit](5)
units: Array[Unit] = Array((), (), (), (), ())
soc
  • 27,983
  • 20
  • 111
  • 215