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
.