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"
}
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
}
private def putOnTable(getCard: () => Option[Card])(implicit table: Table) = getCard() match { case cardOption @ Some(card) => table.addCard(card) cardOption case None => None }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.
stringis not a variable.areYouLazy, likeval notLazyAnymore = string; string.