Why can’t i define a variable recursively in a code block?
scala> {
| val test: Stream[Int] = 1 #:: test
| }
<console>:9: error: forward reference extends over definition of value test
val test: Stream[Int] = 1 #:: test
^
scala> val test: Stream[Int] = 1 #:: test
test: Stream[Int] = Stream(1, ?)
lazy keyword solves this problem, but i can’t understand why it works without a code block but throws a compilation error in a code block.
Note that in the REPL
is evaluated more or less as follows:
So, any
val(ordef, etc) is a member of an internal REPL helper object.Now the point is that classes (and objects) allow forward references on their members:
This is not true for
vals inside a block. In a block everything must be defined in linear order. Thusvals are no members anymore but plain variables (or values, resp.). The following does not compile either:It is not recursion which makes the difference. The difference is that classes and objects allow forward references, whereas blocks do not.