[译]Scala嵌套函数

在Scala中是可以定义嵌套函数的。下面定义了函数factorial,用于计算给定数字的阶乘:

 def factorial(x: Int): Int = {
    def fact(x: Int, accumulator: Int): Int = {
      if (x <= 1) accumulator
      else fact(x - 1, x * accumulator)
    }  
    fact(x, 1)
 }
 println("Factorial of 2: " + factorial(2))
 println("Factorial of 3: " + factorial(3))

程序输出结果是:

Factorial of 2: 2
Factorial of 3: 6

你可能感兴趣的:([译]Scala嵌套函数)