scala 函数中嵌套函数_Scala中的嵌套函数 用法和示例

scala 函数中嵌套函数

Scala中的嵌套函数 (Nested functions in Scala)

A nested function is defined as a function which is defined inside the definition of another function. Programming languages like c, java, etc do not support nested functions but Scala does.

嵌套函数定义为在另一个函数的定义内定义的函数。 诸如c,java等编程语言不支持嵌套函数,但Scala可以。

In Scala, nesting of functions is possible and there can be multiple function definitions to be called inside the definition of a parent function. This concept of defining a function in the definition of another is called Nesting. Like any other code block, a nested function can also be used to define multiple code definitions inside a function.

在Scala中, 函数的嵌套是可能的,并且在父函数的定义内可以调用多个函数定义。 在另一个函数的定义中定义函数的概念称为嵌套。 像任何其他代码块一样, 嵌套函数也可以用于在函数内部定义多个代码定义。

The nested function makes it easier to detect the code and increases modularity. Declaring functions inside another function and using it later when on a specific condition makes it more clearly for further development and redesigning the code.

嵌套函数使检测代码更容易,并增加了模块化。 在另一个函数中声明函数并在特定条件下稍后使用它可以使它更清晰地用于进一步开发和重新设计代码。

Syntax:

句法:

    def function1(){
	    //code block for function 1
	    def function2(){
	        //code block for function 2
        }
    }  

Syntax explanation:

语法说明:

The syntax is used to define the nested function in Scala. Definitions of both functions are standard. But the function 2 is defined inside the code of function 1. Which will be called inside the first one only.

该语法用于在Scala中定义嵌套函数 。 这两个功能的定义都是标准的。 但是功能2是在功能1的代码内定义的。 仅在第一个内部调用。

Example:

例:

object MyClass {
      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)
        }
      def main(args: Array[String]) {
         println("factorial of 10 is " + factorial(10));
         println("factorial of 5 is " + factorial(5));
      }
   }

Code from Nested method in Scala

Scala中嵌套方法的代码

Output

输出量

factorial of 10 is 3628800
factorial of 5 is 120

Code explanation:

代码说明:

The above code is to find the factorial of the given number. It uses a nested function i.e. function fact() declared inside the definition of factorial() function.

上面的代码是查找给定数字的阶乘。 它使用一个嵌套函数,即在factorial()函数定义内声明的事实fact() 。

翻译自: https://www.includehelp.com/scala/nested-functions-in-scala-usage-and-examples.aspx

scala 函数中嵌套函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值