Adrian Adrian - 2 months ago 20x
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
by default), so I expected that
would return a
, not a

The implementation is in TraversableOnce,

def toSeq: Seq[A] = toStream

why is it not overridden in TraversableLike?


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


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


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.