English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Recursive Functions

Scala Functions

Recursive functions play an important role in functional programming languages.

Scala also supports recursive functions.

Recursive functions mean that a function can call itself.

The above example uses a recursive function to calculate the factorial:

object Test {
   def main(args: Array[String]) {
      for (i <- 1 to 10)
         println(i + "The factorial of: =" + factorial(i)
   }
   
   def factorial(n: BigInt): BigInt = {  
      if (n <= 1)
         1  
      else    
      n * factorial(n - 1)
   }
}

Execute the above code, the output result is:

$ scalac Test.scala
$ scala Test
1 The factorial of: = 1
2 The factorial of: = 2
3 The factorial of: = 6
4 The factorial of: = 24
5 The factorial of: = 120
6 The factorial of: = 720
7 The factorial of: = 5040
8 The factorial of: = 40320
9 The factorial of: = 362880
10 The factorial of: = 3628800

Scala Functions