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?
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
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