Home » Scala language

Functions call by name in Scala

In Scala, call by name is used in the case when a program needs to use an expression as arguments for a function. In this tutorial, we will learn how to define and use Scala call by name with a working example?
Submitted by Shivang Yadav, on June 24, 2019

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
    }

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.

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.