I've seen in many examples that sometimes a Seq is being used, while other times is the List…
Is there any difference, other than the former one being a Scala type and the List coming from Java?
collectionslistscalaseq
I've seen in many examples that sometimes a Seq is being used, while other times is the List…
Is there any difference, other than the former one being a Scala type and the List coming from Java?
Best Answer
In Java terms, Scala's
Seq
would be Java'sList
, and Scala'sList
would be Java'sLinkedList
.Note that
Seq
is atrait
, which is equivalent to Java'sinterface
, but with the equivalent of up-and-coming defender methods. Scala'sList
is an abstract class that is extended byNil
and::
, which are the concrete implementations ofList
.So, where Java's
List
is aninterface
, Scala'sList
is an implementation.Beyond that, Scala's
List
is immutable, which is not the case ofLinkedList
. 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 thanList
, 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
andcollection.immutable.Seq
, and it is the latter one that is the "default" imported into scope.There's also
GenSeq
andParSeq
. The latter methods run in parallel where possible, while the former is parent to bothSeq
andParSeq
, 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.