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.
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.
The toSeq() method is utilized to display a sequence from the Scala map. Method Definition: def toSeq: Seq[A] Return Type: It returns a sequence from the stated map.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With