Scala direct reference to nested recursive function
I have this very 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 am getting 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 val foo: ... = ... the line by itself and not nested in def, everything works
+3
source to share
1 answer
You can do this 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 line val foo: ... = ... and not nested in def
it becomes a combination of a field and a getter method, and foo(i-1)
it actually calls the getter method instead of referencing the value you define, which is illegal; but when you have val
inside a method it is just a local variable and has no getter method.
+5
source to share