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.
scala .seq vs .toSeq
Asked Answered
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 Seq
s.
Experiment in the repl shows one difference:
scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)
scala> l.seq
res2: scala.collection.immutable.LinearSeq[Int] = List(1, 2, 3)
scala> l.toSeq
res3: scala.collection.immutable.Seq[Int] = List(1, 2, 3)
The OP says they've already read the API docs, where the difference in return type is clearly indicated, so I'm not sure this is going to be helpful. –
Gerfen
© 2022 - 2024 — McMap. All rights reserved.
.toSeq
as abbreviating.toSequence
and.seq
as.toSequential
. – Gerfen