小白教程
所有教程
关于
Search
172.70.100.206
172.70.100.206
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Nested functions”的源代码
本页内容
上一节:
Higher_order_functions
下一节:
Anonymous_functions
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:内嵌函数}}[[Category:scala functions|7]] = Scala 函数嵌套 = [[scala functions|Scala 函数]] 我们可以在 Scala 函数内定义函数,定义在函数内的函数称之为局部函数。 以下实例我们实现阶乘运算,并使用内嵌函数: <pre> object Test { 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) } } </pre> 执行以上代码,输出结果为: <pre> $ scalac Test.scala $ scala Test 1 1 2 6 </pre> [[scala functions|Scala 函数]]
返回至“
Nested functions
”。
上一节:
Higher_order_functions
下一节:
Anonymous_functions