In practicing with Streams I'm discovering a common pattern of ending a stream like this:
Stream.cons(lastValue, Stream.empty)
This seems like it would be such a common pattern that there is probably a shorthand. Maybe like this?
Stream.finish(lastValue) // Not actual Scala code
Is such a function built into Scala?
The natural choice, Stream(lastValue)
, doesn't work in general because apply
is not lazy, but you can use it when you don't care that you've already assigned the value.
You could possibly use Stream.fill(1)(lastValue)
when you want the value lazily computed, but it's not exactly obvious why one would use this construct (e.g. it makes one wonder if maybe you would want a number other than 1).
I would favor
lastValue #:: Stream.empty
personally.
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