Use-cases for Streams in Scala

The main difference between a Stream and an Iterator is that the latter is mutable and “one-shot”, so to speak, while the former is not. Iterator has a better memory footprint than Stream, but the fact that it is mutable can be inconvenient.

Take this classic prime number generator, for instance:

def primeStream(s: Stream[Int]): Stream[Int] =
  Stream.cons(s.head, primeStream(s.tail filter { _ % s.head != 0 }))
val primes = primeStream(Stream.from(2))

It can be easily be written with an Iterator as well, but an Iterator won’t keep the primes computed so far.

So, one important aspect of a Stream is that you can pass it to other functions without having it duplicated first, or having to generate it again and again.

As for expensive computations/infinite lists, these things can be done with Iterator as well. Infinite lists are actually quite useful — you just don’t know it because you didn’t have it, so you have seen algorithms that are more complex than strictly necessary just to deal with enforced finite sizes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)