为什么我不能在代码块中递归地定义变量?
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, ?)
Run Code Online (Sandbox Code Playgroud)
lazy 关键字解决了这个问题,但我无法理解为什么它没有代码块但在代码块中抛出编译错误.
Deb*_*ski 23
注意在REPL中
scala> val something = "a value"
Run Code Online (Sandbox Code Playgroud)
评估或多或少评估如下:
object REPL$1 {
val something = "a value"
}
import REPL$1._
Run Code Online (Sandbox Code Playgroud)
因此,任何val(或def等)都是内部REPL辅助对象的成员.
现在重点是类(和对象)允许对其成员进行前向引用:
object ForwardTest {
def x = y // val x would also compile but with a more confusing result
val y = 2
}
ForwardTest.x == 2
Run Code Online (Sandbox Code Playgroud)
对于val块内的s,情况并非如此.在一个块中,一切都必须按线性顺序定义.因此,vals不再是成员,而是普通变量(或值,分别).以下内容无法编译:
def plainMethod = { // could as well be a simple block
def x = y
val y = 2
x
}
<console>: error: forward reference extends over definition of value y
def x = y
^
Run Code Online (Sandbox Code Playgroud)
这不是递归,而是产生差异.不同之处在于类和对象允许前向引用,而块不允许.