‹ BACK

Tail recursion optimization

Scala optimizes the tail recursive call:
def bang(x: Int): Int = 
  if (x == 0) throw new Exception("bang!")
  else bang(x - 1)
scala> bang(5)
java.lang.Exception: bang!
      at .bang(<console>:5)
      at .<init>(<console>:6)
Scala only optimizes directly recursive calls back to the same function making the call. If the recursion is indirect, no optimization is possible:
def isEven(x: Int): Boolean =
  if (x == 0) true else isOdd(x - 1)
def isOdd(x: Int): Boolean =
  if (x == 0) false else isEven(x - 1)
You also won't get a tail-call optimization if the final call goes to a function value.
val funValue = nestedFun _
def nestedFun(x: Int) { 
  if (x != 0) { println(x); funValue(x - 1) }
}
Read more: Tail recursion
functions recursion

To check your knowledge the following tests are recommended:
Check your scala scala skills.