Compilation error occurs for the below snippet only when it is method level implementation and error does not occur when it is defined in main. What is the difference ? Scala version used is 2.13.5.
class FibonacciGenerator {
def generate(total: Int): List[Int] = {
val fibSeries: LazyList[Int] = LazyList.cons(1, LazyList.cons(1, fibSeries.zip(fibSeries.tail).map { t => t._1 + t._2 }))
fibSeries.take(total).toList
}
}
Same implementation does not fail below.
object Misc extends App {
val x: LazyList[Int] = LazyList.cons(1, LazyList.cons(1, x.zip(x.tail).map{t => t._1 + t._2}))
println(x)
println(x.take(10).toList)
The difference is that in the latter case you are using objects which are created lazily
An object... is created lazily when it is referenced, like a lazy val.
In the first case it should work if you declare lazy val fibSeries
.