I noticed that method combinations (from here) returns Iterator. It looks reasonable that the method should be "lazy" to avoid generating all combinations in advance. Now I wonder, why it returns Iterator instead of Stream (which is a lazy list in Scala).
So, why does combinations return Iterator rather than Stream ?
With Stream it is more likely that all generated values will be held in memory.
scala> val s = Stream.iterate(0)(_ + 1)
s: scala.collection.immutable.Stream[Int] = Stream(0, ?)
scala> s.drop(3).head
res1: Int = 3
scala> s
res2: scala.collection.immutable.Stream[Int] = Stream(0, 1, 2, 3, ?)
When you retain a reference to your Stream, all generated elements will remain in memory. With an Iterator this is less likely to happen.
Of course this does not have to be the reason why the Scala library is designed the way it is...
I think because Stream caches all previously returned elements, so you would end up with all of them in memory. Iterator only returns the next one
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