Categories
scala

callbyvalue and callbyname in scala

In this post let us learn the topic callbyvalue and callbyname in scala.

Generating random number

Will see how to generate random number before starting the topic. This we are going to use in our further code segment .

  val r = scala.util.Random
  println(r.nextInt)
  println(r.nextInt)
  println(r.nextInt)
  println(r.nextInt)
1242716978
868935609
1888491218
-1140363327

callbyvalue

The value computes before invoking the function . And this use the same value whatever it evaluates everywhere the function invokes . In the below example , the value of a remains same while invoking it for two times .

syntax :

function_name(value_name : datatype)  

   val r = scala.util.Random
  callbyvalue(r.nextInt)
    def callbyvalue (a : Long) : Unit = {
      println(" value of a :" +a)
      println(" value of a :" +a)
    }
 value of a :1644239565
 value of a :1644239565

callbyname

Though we pass the expression , the expression evaluates newly at every time it invoked . In the below example , the value of a varies in each time we invoke .

syntax :

function_name(value_name : =>datatype) 

  val r = scala.util.Random
  callbyname(r.nextInt)
  def callbyname (a : => Long) : Unit = {
    println("value of a :" +a)
    println("value of a :" +a)
  }
value of a :761546004
value of a :-892955369

syntax difference

The syntax difference between callbyvalue and callbyname in scala is highlighted below .

function_name(value_name : datatype)  

function_name(value_name : =>datatype

https://beginnersbug.com/values-variables-and-datatypes-in-scala/