wannabe
wannabe

Reputation: 131

forward reference extends over definition of value

I'm learning nested functions in Scala and here is some code I'm having trouble with

object Main extends App {
    val fac = (x: Int) => {
        val factorial: (Int, Int) => Int = (x, accum) => if (x == 1) accum else factorial(x-1, accum*x)
        factorial(x,1)
    }

    println(fac(3))
}

the compiler gives this error:

forward reference extends over definition of value factorial

val factorial: (Int, Int) => Int = (x, accum) => if (x == 1) accum else factorial(x-1, accum*x)**

what am I doing wrong?

Upvotes: 0

Views: 3145

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37832

You should declare factorial using def and not val:

  • Using val means it's a value, evaluated once, at declaration; Therefore, it's easy to see why the compiler can't use that definition while evaluating it
  • Using def means it's a method, evaluated separately for every call, therefore supporting referencing itself within the definition (recursion)

Perhaps a less-confusing way to write this would be to declare this method as a method that expects arguments, instead of a method that returns a function which expects these arguments:

val fac = (x: Int) => {
  def factorial(x: Int, accum: Int): Int = if (x == 1) accum else factorial(x-1, accum*x)
  factorial(x,1)
} 

Upvotes: 4

Related Questions