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
原文地址:https://www.cnblogs.com/zhouwenyang/p/13886016.html