Adrian Adrian - 3 months ago 35
Scala Question

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?

Answer

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

Comments