Evaluating by-name parameters only once

Let's imagine that we have an application that takes data about people from a database. The reading operation is something that is expensive, and it is a good candidate for lazy evaluation. For this example, we will simply simulate reading from the database. First of all, our model will be as simple as the following:

case class Person(name: String, age: Int)

Now, let's create a companion object that will have a method that simulates getting the data about people from a database:

object Person {  def getFromDatabase(): List[Person] = {    // simulate we're getting people from database by sleeping    System.out.println("Retrieving people...")    Thread.sleep(3000)    List(      Person("Ivan", 26),      Person("Maria", 26)

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.