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))
def factorial(x: Int): Int =
  def fact(x: Int, accumulator: Int): Int =
    if x <= 1 then 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

此页面的贡献者