Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala shorthand for ending a stream?

Tags:

scala

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?

like image 359
Cory Klein Avatar asked Dec 25 '22 10:12

Cory Klein


1 Answers

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.

like image 94
Rex Kerr Avatar answered Jan 11 '23 14:01

Rex Kerr