Argument evaluation

When we call a method (or a function), we could ask for delayed argument evaluation. Following is an example Scala snippet:

scala> def aMethod(x: String) = 
     |   println(x) 
aMethod: (x: String)Unit 
 
scala> aMethod("Hello world") // call site 
Hello world  

The method argument is evaluated at the call site. However, recall that functions are first class values. This allows us to write the method as follows:

scala> def aMethod_1(x: () => String) = 
     |   println(x()) // argument evaluated 
aMethod_1: (x: () => String)Unit 
 
scala> aMethod_1(() => "Hello world") // unevaluated argument  
Hello world 

When aMethod_1 is called, the string argument is not evaluated at the call site. Inside the method definition, the function is called and the argument ...

Get Learning Functional Data Structures and Algorithms now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.