I have this really simple method definition with a nested recursive function:
def bar(arr : Array[Int]) : Int = {
val foo : Int => Int = (i: Int) => if(i == 0) 0 else i + foo(i-1)
foo(3)
}
But I get this error:
<console>:36: error: forward reference extends over definition of value foo
val foo : Int => Int = (i: Int) => if(i == 0) 0 else i + foo(i-1)
^
If I just put the val foo: ... = ... line by itself, and not nested within a def, everything works
You can make it a
lazy val
:or a
def
:When you
it becomes a combination of a field and a getter method, and
foo(i-1)
actually calls the getter method instead of referring to the value you are defining, which is illegal; but when you have aval
inside a method, it's just a local variable and doesn't have a getter method.