1
votes

In Scala, why is Unit an Anyval ? What does it mean semantically ? Why not an Any or Anyref?

Semantically what is the difference and what is the rational behind that choice?

2

2 Answers

3
votes

You can't have a Unit variable with value null.

However, Unit can be boxed in the usual sense:

scala> def f[A](a: A) = 42
f: [A](a: A)Int

scala> f(())
res0: Int = 42

scala> :javap -pv -
[snip]
        12: getstatic     #41                 // Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit;
        15: invokevirtual #45                 // Method $line3/$read$$iw$$iw$.f:(Ljava/lang/Object;)I

Similarly,

scala> var x: Unit = _
x: Unit = ()

is really BoxedUnit.UNIT under the hood.

The "unboxed" type BoxedUnit.TYPE is Void.TYPE.

0
votes

It's pretty clear described into scala docs:

.. There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void.