O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Call by name

Typically, parameters are passed by value are by-value that is the value of the parameter is determined before it gets passed to the function. In the REPL session here, we have two functions, g and f.

We pass the value of calling getValue() to f and g:

scala> var k = 0 
k: Int = 0 
scala> def getVal() = { 
     |   k += 1 
     |   k 
     | } 
getVal: ()Int 
scala> def g(i: Int) = { 
     |   println(s"${i}") 
     |   println(s"${i}") 
     |   println(s"${i}") 
     | } 
g: (i: Int)Unit 

scala> g(getVal())
1 
1 
1 

Refer to the following figure:

Call by name

Figure 4.6: Call By Value

The three println statements in g() print the same value, 1:

scala> def f(i: => Int) = {  
 | println(s"${i}") ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required