嵌套函数(Nested Functions)
优质
小牛编辑
138浏览
2023-12-01
Scala允许您在函数内定义函数,在其他函数内定义的函数称为local functions 。 这是一个阶乘计算器的实现,我们使用传统技术调用第二个嵌套方法来完成工作。
尝试以下程序来实现嵌套函数。
例子 (Example)
object Demo {
def main(args: Array[String]) {
println( factorial(0) )
println( factorial(1) )
println( factorial(2) )
println( factorial(3) )
}
def factorial(i: Int): Int = {
def fact(i: Int, accumulator: Int): Int = {
if (i <= 1)
accumulator
else
fact(i - 1, i * accumulator)
}
fact(i, 1)
}
}
将上述程序保存在Demo.scala 。 以下命令用于编译和执行此程序。
Command
\>scalac Demo.scala
\>scala Demo
输出 (Output)
1
1
2
6
与许多语言中的局部变量声明一样,嵌套方法仅在封闭方法中可见。 如果您尝试在factorial() fact()之外调用fact() factorial() ,则会出现编译器错误。