为什么我不能在代码块中递归定义一个变量? [英] Why can't i define a variable recursively in a code block?

查看:52
本文介绍了为什么我不能在代码块中递归定义一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能在代码块中递归定义一个变量?

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 关键字解决了这个问题,但我不明白为什么它在没有代码块的情况下工作,但在代码块中引发编译错误.

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.

推荐答案

注意在 REPL 中

scala> val something = "a value"

或多或少的评估如下:

object REPL$1 {
  val something = "a value"
}
import REPL$1._

因此,任何 val(或 def 等)都是内部 REPL 辅助对象的成员.

So, any val(or def, etc) is a member of an internal REPL helper object.

现在的重点是类(和对象)允许对其成员进行前向引用:

Now the point is that classes (and objects) allow forward references on their members:

object ForwardTest {
  def x = y // val x would also compile but with a more confusing result
  val y = 2
}
ForwardTest.x == 2

这不适用于块内的 val .在块中,所有内容都必须以线性顺序定义.因此 val 不再是成员,而是普通变量(或值).以下也不能编译:

This is not true for vals inside a block. In a block everything must be defined in linear order. Thus vals are no members anymore but plain variables (or values, resp.). The following does not compile either:

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
             ^

造成区别的不是递归.区别在于类和对象允许前向引用,而块则不允许.

It is not recursion which makes the difference. The difference is that classes and objects allow forward references, whereas blocks do not.

这篇关于为什么我不能在代码块中递归定义一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆