7

When I input Seq(1,2,3) in REPL, it returns me List(1,2,3)

scala> Seq(1,2,3)
res8: Seq[Int] = List(1, 2, 3)

Therefore, I thought the List(1,2,3) may be of type List[Int]. And I tried to specify the type for the variable who are assigned to Seq(1,2,3), but unexpectedly, the REPL complains like this:

scala> val a:List[Int]=Seq(1,2,3)
<console>:20: error: type mismatch;
 found   : Seq[Int]
 required: List[Int]
       val a:List[Int]=Seq(1,2,3)

Does anyone have ideas about what Seq[Int] = List(1, 2, 3) mean? Shouldn't it mean Seq(1,2,3) returns a list? What is the difference between Seq[Int] and List[Int]? And how to convert between Seq and List?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237

1 Answers1

10

Seq is a base trait (interface) for sequences and List is a concrete implementation of that interface.

Every instance of List is already a Seq so there's no need to convert anything. You can use toSeq method, but I don't see any reason to do so. To convert Seq to a List use toList method.

Rado Buransky
  • 3,252
  • 18
  • 25
  • This is still confusing, i.e. `Seq` can be instantiated (or has a builder), but digging up the implementation differences of a list is not straightforward. And instantiating a `Seq` yields a `List` (in the REPL at least). – matanster Mar 21 '16 at 22:40
  • 3
    Asking for a `Seq` has the same meaning as asking for "a car". Any car. And the factory gets you a nice Toyota - in our case an instance of `List`. Your request was generic and the response is specific. If you want Toyota ask for it directly - explicitly instatiate a `List`. – Rado Buransky Mar 22 '16 at 05:58