Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

scala - Why can't i define a variable recursively in a code block?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note that in the REPL

scala> val something = "a value"

is evaluated more or less as follows:

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...