Search code examples
listscalavectorscala-collectionsseq

How does usage of Seq compare to that of List, Array and Vector?


At SO, I have seen questions that compare Array with Seq, List with Seq and Vector with well, everything. I do not understand one thing though. When should I actually use a Seq over any of these? I understand when to use a List, when to use an Array and when to use a Vector. But when is it a good idea to use Seq rather than any of the above listed collections? Why should I use a trait that extends Iterable rather than all the concrete classes listed above?


Solution

  • You usually should use Seq as input parameter for method or class, defined for sequences in general (just general, not necessarily with generic):

    def mySort[T](seq: Seq[T]) = ...
    case class Wrapper[T](seq: Seq[T]) 
    implicit class RichSeq[T](seq: Seq[T]) { def mySort = ...}
    

    So now you can pass any sequence (like Vector or List) to mySort.

    If you care about algorithmic complexity - you can specialize it to IndexedSeq (quick random element access) or LinearSeq (fast memory allocation). Anyway, you should prefer most top-level class if you want your function to be more polymorphic has on its input parameter, as Seq is a common interface for all sequences. If you need something even more generic - you may use Traversable or Iterable.