Lifu Huang Lifu Huang - 2 months ago 5
Scala Question

What's the difference between scala.List and scala.collection.immutable.List?

I'm new to Scala. And I noticed that

List
exists in both
scala
and
scala.collection.immutable
. At the beginning, I thought scala.List is just an alias for scala.collection.immutable.List. But later I found that:

scala> typeOf[scala.List[A]]
res1: reflect.runtime.universe.Type = scala.List[A]

scala> typeOf[scala.collection.immutable.List[A]]
res2: reflect.runtime.universe.Type = List[A]


As shown above, the
typeof
on these two
List
s give different results, which make me doubious about my judgement.

I would like to know:
Are scala.List and scala.collection.immutable.List the same thing?
If yes, why
typeOf
gives different results as shown above?
If no, what are the differences?

Thanks!

Answer

As @Patryk mentioned in comment, it is an alias for scala.collection.immutable.List.

If you look at scala\package.scala:

  type List[+A] = scala.collection.immutable.List[A]
  val List = scala.collection.immutable.List

So fundamentally they are the same:

scala> implicitly[scala.List[Int] =:= scala.collection.immutable.List[Int]]
res19: =:=[List[Int],List[Int]] = <function1>

scala> :type List
scala.collection.immutable.List.type

scala> :type scala.collection.immutable.List
collection.immutable.List.type

What you are using is I believe typeOf from import scala.reflect.runtime.universe._. Which is a reflective representation of the type parameter and hence it gave you just scala.List (which is correct behavior in my opinion)