Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does method "combinations" return Iterator rather than Stream in Scala?

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 ?

like image 493
Michael Avatar asked Nov 25 '25 12:11

Michael


2 Answers

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

like image 57
ziggystar Avatar answered Nov 28 '25 01:11

ziggystar


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

like image 39
The Archetypal Paul Avatar answered Nov 28 '25 03:11

The Archetypal Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!