Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is TraversableOnce.toSeq returning a Stream?

Here is an example:

scala> val xs = List(1,2,3).toIterator.toSeq
xs: Seq[Int] = Stream(1, ?)

A sequence is a materialized collection (it's a List by default), so I expected that toSeq would return a List, not a Stream

The implementation is in TraversableOnce,

  def toSeq: Seq[A] = toStream

why is it not overridden in TraversableLike?

like image 668
Adrian Avatar asked Oct 17 '14 19:10

Adrian


1 Answers

Scala supports infinite iterators, and Stream is the simplest Seq for possible infinite data.

Iterator.from(1).toSeq

terminates (if only a part of the collection is used), but

Iterator.from(1).toList

will never terminate.

You don't want do break code, if an equally valid decision would not. The toSeq method doesn't know the origin of the Iterator, therefor it must assume that it could be infinite.

The Docs "explain" this decision like this:

Converts this traversable or iterator to a sequence. As with toIterable, it's lazy in this default implementation, as this TraversableOnce may be lazy and unevaluated. Note: will not terminate for infinite-sized collections.

http://www.scala-lang.org/api/current/?_ga=1.200291566.1390086478.1406220121#scala.collection.Iterator

like image 136
bmaderbacher Avatar answered Nov 06 '22 08:11

bmaderbacher