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 1def 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) accumulatorelse 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 120Code 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 函數中嵌套函數
總結
以上是生活随笔為你收集整理的scala 函数中嵌套函数_Scala中的嵌套函数 用法和示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: List 去重的 6 种方法,这个方法最
- 下一篇: 详解4种经典的限流算法