In Scala, if a function calls itself in the last step (you must call yourself completely, but you cannot add additional operators), the function stack will be reused in Scala, in this way, recursive calls are converted into linear calls, greatly improving the efficiency.
If a function callitself as its last action, the function's stack frame can be reused. This is called tail recursion.
=> Tail recursive functions are iterative process
Two versions of factorial functions are implemented here. One is a common method, and the other is a tail recursive optimization.
/*In Scala, only directly recursive call to the current function are optimized.One can require that a function is tail-recursive using a @tailrec annotation: @tailrec def gcd(a: Int, b: Int): Int = ...If the annotation is given, and the implementation of gcd were nottail recursive, an error would be issued.*/import scala.annotation.tailrecobject exercise { def factorial(n: Int): Int = if (n == 0) 1 else n * factorial(n-1) //a tail recursive version of factorial def factorialTailRecursion(n: Int): Int = { @tailrec def loop(acc: Int, n: Int): Int = if (n == 0) acc else loop(acc * n, n-1) loop(1, n) } factorial(4) factorialTailRecursion(4) //optimized! the function‘s stack frame can be reused!}
Scala tail recursive optimization, reuse function Stack