Hopefully this is just the first of many posts about Scala.
Random.alphanumeric produces a stream of type
Stream[Char]. It’s interesting that Streams are “immutable” even though they’re lazy (elements are only evaluated when they are needed). This is because the “elements” of the stream are immutable (even though some haven’t been realised yet). If we keep a reference to the stream, we can confirm that it always produces the same output.
The Stream stores computed values, so Streams can be used to memoize algorithms. This also means we have to be wary of the memory usage when consuming the Stream.
The scala doc for
Stream has this neat (and rather mind-bending) example:
Once I wrapped my head around what
zip does with Streams, I was still surprised by the way
map is applied “just in time” to generate the next element of the tail. My functional programming chops are still not that juicy, but I get a sense of something quite powerful here.