MaatDeamon
MaatDeamon

Reputation: 9761

Why is Unit an Anyval ? What does it mean semantically?

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?

Upvotes: 1

Views: 276

Answers (2)

som-snytt
som-snytt

Reputation: 39577

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.

Upvotes: 3

vvg
vvg

Reputation: 6385

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.

Upvotes: 0

Related Questions