When does a Stream need to be lazy?

Viewed 577

The following are both meant to create a Stream of integers:

val s: Stream[Int] = 1 #:: s.map(_ + 1)

def makeStream = {
  val s: Stream[Int] = 1 #:: s.map(_ + 1)
  s
}

The first is fine; however the makeStream method won't compile:

error: forward reference extends over definition of value s
  val s: Stream[Int] = 1 #:: s.map(_ + 1)
                             ^

It only compiles if we make s a lazy val. Why does it need to be a lazy val in a method, but not outside?

1 Answers
Related