Call by Value and Call by Name Parameters

    While you define Methods with arguments, there are two ways of parameter passing:

    Call by Value: Those parameters that are already evaluated when they are passed to a function.

    Syntax :    parameter: parameterType

    Call by Name : These are the parameters that are not already evaluated but will be evaluated each time a call to function is made.

    Syntax : parameter :=> parameterType

    Example :

    def callByValue(num: Int) = {
      println(s"First fetch: $num. Second fetch: $num")
    }
    
    callByValue(scala.util.Random.nextInt)
    callByValue(scala.util.Random.nextInt)
    
    def callByName(num: => Int) = {
      println(s"First fetch: $num. Second fetch: $num")
    }
    
    callByName(scala.util.Random.nextInt)
    
    callByName(scala.util.Random.nextInt)

    Output:

    First fetch: 1917657572. Second fetch: 1917657572
    First fetch: -1411166275. Second fetch: -1411166275
    First fetch: -276172407. Second fetch: 908226387
    First fetch: 397353949. Second fetch: 1896525012