Home »
Scala
Functions call by name in Scala
By IncludeHelp Last updated : October 10, 2024
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.
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.
Syntax
def functionName(parameter => Datatype){
//Function body... contains the call by name call to the code block
}
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.
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.