I see from Scala hierarchy that AnyVal
is super type for scala.Unit
, Boolean
, Char
and other Number
types.
scala> val list1 = List((), 1 )
list: List[AnyVal] = List((), 1) // I see this is valid when compared with hierarchy tree.
scala> val list2 = List(Unit, 1 )
list: List[Any] = List(object scala.Unit, 1) // Why???
I see list1
is of type AnyVal
where as list2
is of type Any
, even though they have same data (I assume).
Is ()
not same as Scala.Unit
? What am I missing here?
To answer your question, ()
is a value of type scala.Unit
. Whereas, scala.Unit
is the companion object, so it is of type Unit.type
.
Have a look in the REPL code below:
scala> (): scala.Unit
// (): scala.Unit
scala> scala.Unit
// res1: Unit.type = object scala.Unit
Bottom line is any object you pass to a covariant list will find the type common to the values. See discussion in Why doesn't the example compile, aka how does (co-, contra-, and in-) variance work?
As you discovered, the common type of Integer
and scala.Unit
is AnyVal
. The common type of Intger
and Unit.type
is Any
.
There are 3 distinct entities:
1) type scala.Unit
2) object ()
- the only member of the class scala.Unit
3) object scala.Unit
- a companion object of 1)
. It is a member of class scala.Unit$
- not the same as scala.Unit
.
In your first example ()
stands for 1)
, in the second Unit
stands for 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With