Anton Kuzmin
Anton Kuzmin

Reputation: 831

Lazy function arguments?

How to make "areYouLazy" function evaluate "string" only once the best possible way?

def areYouLazy(string: => String) = {
    string
    string
  }

areYouLazy {
  println("Generating a string")
  "string"
} 

Upvotes: 1

Views: 123

Answers (1)

Jean Logeart
Jean Logeart

Reputation: 53859

Call-by-name arguments are executed everytime you access them.

To avoid multiple executions, you can simply use a lazy cache value that is executed only the first time it is accessed:

def areYouLazy(string: => String) = {
  lazy val cache = string
  cache  // executed
  cache  // simply access the stored value
}

Upvotes: 7

Related Questions