By Alvin Alexander. Last updated: July 16, 2018
I'm actually on vacation this week, but last night I showed a friend how to write software in Scala. He's familiar with recursion, so we jumped right into a simple factorial recursion example:
object FactorialRecursion { def main(args: Array[String]) { println(factorial(5)) } def factorial(n: Int): Int = { if (n == 0) return 1 else return n * factorial(n-1) } }
Another way to write that factorial method is this:
def factorial(n: Int): Int = n match { case 0 => 1 case _ => n * factorial(n-1) }
Since I'm on vacation this week I won't take the time to explain this, but I'll provide this hint, that shows how to factorial function works for each number:
5 * factor(4) = 5 * 24 = 120 4 * factor(3) = 4 * 6 = 24 3 * factor(2) = 3 * 2 = 6 2 * factor(1) = 2
Please note that there are ways to improve upon this. See this URL for many more Scala recursion examples.