O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

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

Let’s Get Lazy

If you’re new to lazy evaluation, you probably have used it without really calling it that. Many languages support short-circuit evaluation for conditions. If the evaluation of an argument in a condition with multiple && or || is enough to determine the truth, then the remaining arguments in that expression are not evaluated. Here’s an example of a simple short-circuit evaluation.

Parallel/shortCircuit.scala
 
def​ expensiveComputation() = {
 
println(​"...assume slow operation..."​)
 
false
 
}
 
 
def​ evaluate(input: ​Int​) = {
 
println(s​"evaluate called with $input"​)
 
if​(input >= 10 && expensiveComputation())
 
println(​"doing work..."​)
 
else
 
println(​"skipping"​)
 
}
 
 
evaluate(0)
 
evaluate(100)

The expensiveComputation ...

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