如何使"areYouLazy"函数仅以最佳方式评估"字符串"?
def areYouLazy(string: => String) = {
string
string
}
areYouLazy {
println("Generating a string")
"string"
}
Run Code Online (Sandbox Code Playgroud)
每次访问时都会执行按名称调用的参数.
要避免多次执行,您只需使用lazy仅在第一次访问时执行的缓存值:
def areYouLazy(string: => String) = {
lazy val cache = string
cache // executed
cache // simply access the stored value
}
Run Code Online (Sandbox Code Playgroud)