Noel Yap Noel Yap - 7 days ago 5
Scala Question

More terse way to define Scala Stream object?

I have the following:

val notDivisibleBy2: Stream[Long] = 3L #:: 5L #:: notDivisibleBy2.tail.map(_ + 2)
println(notDivisibleBy2.take(3))


If
5L
is removed, a
StackOverflow
is emitted. Is there a way to have the tail calculation work so that
5L
doesn't have to be specified?

Answer

You are entering an infinite loop when you remove 5L and then call the tail function. As you can see, the tail of notDivisibleBy2 is notDivisibleBy2.tail.map(_ + 2). You therefore need to remove both 5L and the call to tail.

val notDivisibleBy2: Stream[Long] = 3L #:: notDivisibleBy2.map(_ + 2)