Difference between a Seq and a List in Scala
Solution 1:
In Java terms, Scala's Seq
would be Java's List
, and Scala's List
would be Java's LinkedList
.
Note that Seq
is a trait
, which is equivalent to Java's interface
, but with the equivalent of up-and-coming defender methods. Scala's List
is an abstract class that is extended by Nil
and ::
, which are the concrete implementations of List
.
So, where Java's List
is an interface
, Scala's List
is an implementation.
Beyond that, Scala's List
is immutable, which is not the case of LinkedList
. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).
Scala's List
is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days, Vector
is a better choice than List
, but habit is hard to break.
Seq
is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: collection.Seq
, collection.mutable.Seq
and collection.immutable.Seq
, and it is the latter one that is the "default" imported into scope.
There's also GenSeq
and ParSeq
. The latter methods run in parallel where possible, while the former is parent to both Seq
and ParSeq
, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.
Solution 2:
A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply()
for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList.
A List is a Seq that is implemented as an immutable linked list. It's best used in cases with last-in first-out (LIFO) access patterns.
Here is the complete collection class hierarchy from the Scala FAQ:
Solution 3:
Seq
is a trait that List
implements.
If you define your container as Seq
, you can use any container that implements Seq
trait.
scala> def sumUp(s: Seq[Int]): Int = { s.sum }
sumUp: (s: Seq[Int])Int
scala> sumUp(List(1,2,3))
res41: Int = 6
scala> sumUp(Vector(1,2,3))
res42: Int = 6
scala> sumUp(Seq(1,2,3))
res44: Int = 6
Note that
scala> val a = Seq(1,2,3)
a: Seq[Int] = List(1, 2, 3)
Is just a short hand for:
scala> val a: Seq[Int] = List(1,2,3)
a: Seq[Int] = List(1, 2, 3)
if the container type is not specified, the underlying data structure defaults to List
.
Solution 4:
In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :
sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...
[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]