Is there anything what could be improved on this code?
def factorial(n: Int, offset: Int = 1): Int = {
if(n == 0) offset else factorial(n - 1, (offset * n))
}
The idea is to have tail-recursive version of factorial in Scala, without need to define internal function or alias.
This one is callable like this:
factorial(4)
So final solution looks like this:
import scala.annotation._
@tailrec
def factorial(n: Int, accumulator: Long = 1): Long = {
if(n == 0) accumulator else factorial(n - 1, (accumulator * n))
}
tail-recursive
approach (more here stackoverflow.com/questions/33923/what-is-tail-recursion ) \$\endgroup\$