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 = 70
Code 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 函数调用