Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 349
mp94 Avatar asked Oct 10 '14 18:10

mp94


People also ask

What is the difference between SEQ and list in Scala?

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.

What is toSeq in Scala?

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.


1 Answers

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.

like image 98
Travis Brown Avatar answered Sep 17 '22 04:09

Travis Brown