Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Self-Recursive val in function [duplicate]

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.

like image 513
senia Avatar asked Nov 23 '22 07:11

senia


2 Answers

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.

like image 158
Debilski Avatar answered Feb 12 '23 15:02

Debilski


I'll add that when you write:

object O {
  val x = y
  val y = 0
}

You are actually writing this:

object O {
  val x = this.y
  val y = 0
}

That little this is what is missing when you declare this stuff inside a definition.

like image 40
Daniel C. Sobral Avatar answered Feb 12 '23 15:02

Daniel C. Sobral