1

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"
} 
2
  • I don't think it's possible, because your string is not a variable. Commented Oct 4, 2014 at 16:03
  • You can assign it to a variable in areYouLazy, like val notLazyAnymore = string; string. Commented Oct 4, 2014 at 16:04

1 Answer 1

7

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I ended up doing it through a function. Seems more readable. Less names to give to variables. private def putOnTable(getCard: () => Option[Card])(implicit table: Table) = getCard() match { case cardOption @ Some(card) => table.addCard(card) cardOption case None => None }
@HappyCoder - I don't understand why you think getCard isn't an extra name. Also, it's harder to pass an argument to () => A than to => A. There might be reasons to do it your way, but "more readable" and "fewer names" aren't among them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.