scala 函数调用_在Scala中按名称调用函数
scala 函數調用
函數按名稱調用 (Functions call by name )
By default, the method of parameter passing in a programming language is "call by value". In this, the parameter is passed to a function which makes a copy of them an operates on them. In Scala also, the call by name is the default parameter passing method.
默認情況下,以編程語言傳遞參數的方法是“按值調用” 。 在這種情況下,參數被傳遞給一個函數,該函數使它們的副本對它們進行操作。 同樣在Scala中,按名稱調用是默認的參數傳遞方法。
Call by name is used in Scala when the program needs to pass an expression or a block of code as a parameter to a function. The code block passed as call by name in the program will not get executed until it is called by the function.
當程序需要將表達式或代碼塊作為參數傳遞給函數時, 在Scala中使用按名稱調用 。 在程序中按名稱傳遞作為調用傳遞的代碼塊,直到函數調用該代碼塊后,才能執行。
Syntax:
句法:
def functionName(parameter => Datatype){//Function body... contains the call by name call to the code block}Explanation:
說明:
This syntax initializes a call by name function call. Here the function's argument passed is a function and the datatype is the return type of the function that is called. The function body executes the call by name call to the function that evaluates to provide the value. The call is initiated by using the parameter name as specified in the program.
此語法通過名稱函數call初始化調用 。 這里傳遞的函數參數是一個函數,數據類型是所調用函數的返回類型。 函數主體通過名稱調用執行對要評估以提供值的函數的調用。 通過使用程序中指定的參數名稱來啟動該調用。
Example:
例:
object Demo {def multiply(n : Int) = {(14*5);}def multiplier( t: => Long ) = {println("Code to multiply the value by 5")println("14 * 5 = " + t)}def main(args: Array[String]) {println("Code to show call by name")multiplier(multiply(14))} }Output
輸出量
Code to show call by name Code to multiply the value by 5 14 * 5 = 70Code explanation:
代碼說明:
The above code is to display the use of call by name. The code prints the number multiplied by 5. The number in the code is 14. That is passed to the call by name function at the time of function call form the main call. The in the multiplier function after the code it needs to execute the multiply method is initiated and value is evaluated there to be returned to the calling function which prints the value i.e. 70.
上面的代碼是按名稱顯示呼叫的使用 。 該代碼將打印乘以5的數字。代碼中的數字為14。在從主調用進行函數調用時,該函數將傳遞給按名稱調用。 在乘法器函數中,需要執行乘法方法的代碼啟動后,在其中求值,然后返回到打印該值(即70)的調用函數。
翻譯自: https://www.includehelp.com/scala/functions-call-by-name-in-scala.aspx
scala 函數調用
總結
以上是生活随笔為你收集整理的scala 函数调用_在Scala中按名称调用函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 奇瑞瑞虎3多少钱啊?
- 下一篇: 拖车一公里多少钱啊?