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
:
def bar(arr : Array[Int]) : Int = {
lazy val foo : Int => Int = (i: Int) => if(i == 0) 0 else i + foo(i-1)
foo(3)
}
or a def
:
def bar(arr : Array[Int]) : Int = {
def foo(i: Int): Int = if(i == 0) 0 else i + foo(i-1)
foo(3)
}
When you
put the val foo: ... = ... line by itself, and not nested within a def
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 a val
inside a method, it's just a local variable and doesn't have a getter method.