Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Recursive Functions

Scala Recursive Functions

Scala functions Scala Functions

Recursive functions play an important role in functional programming languages.

Scala also supports recursive functions.

A recursive function means a function can call itself.

The example above uses a recursive function to compute factorial:



object Test {

   def main(args: Array[String]) {

      for (i <- 1 to 10)

         println(i + " 的阶乘为: = " + factorial(i) )

   }

   

   def factorial(n: BigInt): BigInt = {  

      if (n <= 1)

         1  

      else    

      n * factorial(n - 1)

   }

}

The output of the code above is:



$ scalac Test.scala

$ scala Test

1 的阶乘为: = 1

2 的阶乘为: = 2

3 的阶乘为: = 6

4 的阶乘为: = 24

5 的阶乘为: = 120

6 的阶乘为: = 720

7 的阶乘为: = 5040

8 的阶乘为: = 40320

9 的阶乘为: = 362880

10 的阶乘为: = 3628800

Scala functions Scala Functions