Lifu Huang
Lifu Huang

Reputation: 12768

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 Lists 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!

Upvotes: 0

Views: 190

Answers (2)

Jatin
Jatin

Reputation: 31724

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)

Upvotes: 2

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

scala.List is type alias for scala.collection.immutable.List

package scala

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

Anything under the package scala is by default available you don't have to explicitly import it.

As List is something which is widely used it makes perfect sense if it is available by default in the context rather than importing. That is why a type alias of the scala.collection.immutable.List is in package scala.

typeOf must be showing the higher preference package by default.

Upvotes: 0

Related Questions