scala streams
Lazy Instantiation is a common pattern in software. I’ve seen it be used in dependency injection inside a web service. It turns out that Scala offers a similar behavior in their Stream class.
Here’s how I understand it:
- a
List
in Scala comprises of ahead
element, which is the first item in the list - it also comprises of a
tail
, which are all the other elements.
A Stream
is similar to a list, but the difference is that the tail
hasn’t been fully computed at the time of instantiation. From what I’ve been reading, applying this concept of Lazy Evaluation to a collection is a standard feature of functional programming.
While a Stream
is theoretically infinite, it is possible to force an evaluation of the full stream which will quickly blow the memory on your JVM:
I’m having trouble thinking of use cases for everyday programming, but I can imagine Stream
s being a powerful tool for algorithms. For example here’s a use case for the classic factorial solve:
I’ve also seen some examples of prime number sieves using this Stream
class. I hope to explore that in a future post.