Search code examples
scalacollectionsseq

scala .seq vs .toSeq


In the Scala documentation, collections have both .seq and a .toSeq method defined on them. What is the difference between them, and why are they both there? I wasn't able to figure it out from reading the Scala collection documentation.


Solution

  • Suppose I've got a parallel collection:

    val myParList = List(1, 2, 3, 4).par
    

    Now operations like map on this collection will be run in parallel. Usually this is great, since it means stuff gets done faster, but sometimes you really do need to perform some kind of side effecting operation on the elements, and then running in parallel can cause problems:

    scala> myParList.foreach(println)
    1
    4
    3
    2
    

    .seq allows you to fix this by requiring the operations to run sequentially (without copying the contents of the collection):

    scala> myParList.seq.foreach(println)
    1
    2
    3
    4
    

    In effect it just undoes .par. .toSeq doesn't provide the same guarantee, and in general it's only useful on subclasses of GenTraversableOnce that aren't already Seqs.