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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

1

It was fixed for Scala 2.9 and now prints :

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.