49 Lazy evaluation

 

After reading this lesson, you’ll be able to

  • Implement functions that use by-name parameters
  • Initialize a value lazily by using the keyword lazy

Now that you’ve mastered JSON serialization and deserialization, you’ll learn about lazy evaluation. You already encountered examples of lazy evaluations when discussing Scala collections. For example, the function getOrElse(key: K, default: => V) acting on an instance of type Map[K,V] has two parameters: key, which is eagerly evaluated (or called by value), and default, which is lazily evaluated (or called by name). In this lesson, you’ll see how to evaluate parameters by name (i.e., lazy evaluation), rather than by value (i.e., eager evaluation). You’ll also learn how to initialize values lazily using the keyword lazy. This can be useful when its initialization is expensive either in terms of time or resources. In the capstone, you’ll implement the logic and API layer of your quiz application using a type called IO, which allows you to represent computations lazily.

49.1 By-name parameters

49.2 Lazy values

Summary

Answers to quick checks