Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is scala.Unit not same as ()?

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?

like image 982
Puneeth Reddy V Avatar asked Nov 23 '18 09:11

Puneeth Reddy V


2 Answers

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.

like image 133
Amit Prasad Avatar answered Sep 28 '22 05:09

Amit Prasad


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)

like image 42
simpadjo Avatar answered Sep 28 '22 07:09

simpadjo