I wanted to memoize this:

def fib(n: Int) = if(n <= 1) 1 else fib(n-1) + fib(n-2) println(fib(100)) // times out

So I wrote this and this surprisingly compiles and works (I am surprised because fib references itself in its declaration):

case class Memo[A,B](f: A => B) extends (A => B) { private val cache = mutable.Map.empty[A, B] def apply(x: A) = cache getOrElseUpdate (x, f(x)) } val fib: Memo[Int, BigInt] = Memo { case 0 => 0 case 1 => 1 case n => fib(n-1) + fib(n-2) } println(fib(100)) // prints 100th fibonacci number instantly

But when I try to declare fib inside of a def , I get a compiler error:

def foo(n: Int) = { val fib: Memo[Int, BigInt] = Memo { case 0 => 0 case 1 => 1 case n => fib(n-1) + fib(n-2) } fib(n) }

Above fails to compile error: forward reference extends over definition of value fib case n => fib(n-1) + fib(n-2)

Why does declaring the val fib inside a def fails but outside in the class/object scope works?

To clarify, why I might want to declare the recursive memoized function in the def scope - here is my solution to the subset sum problem: