Scala 惰性函数参数?

Scala 惰性函数参数?,scala,Scala,如何使“areYouLazy”函数只对“string”求值一次是最好的方法 def areYouLazy(string: => String) = { string string } areYouLazy { println("Generating a string") "string" } 每次访问按名称调用参数时都会执行这些参数 为了避免多次执行,您只需使用仅在第一次访问时执行的惰性缓存值: def areYouLazy(string: => S

如何使“areYouLazy”函数只对“string”求值一次是最好的方法

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

areYouLazy {
  println("Generating a string")
  "string"
} 
每次访问按名称调用参数时都会执行这些参数

为了避免多次执行,您只需使用仅在第一次访问时执行的
惰性
缓存值:

def areYouLazy(string: => String) = {
  lazy val cache = string
  cache  // executed
  cache  // simply access the stored value
}
每次访问按名称调用参数时都会执行这些参数

为了避免多次执行,您只需使用仅在第一次访问时执行的
惰性
缓存值:

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

我认为这是不可能的,因为你的
string
不是一个变量。你可以在
areYouLazy
中将它分配给一个变量,比如
val notlazyore=string;string
。我认为这是不可能的,因为您的
string
不是一个变量。您可以在
areYouLazy
中将其分配给变量,如
val notlazyore=string;字符串
。谢谢!我最终通过一个函数完成了它。看起来更具可读性。给变量的名称更少
private def putOnTable(getCard:()=>Option[Card])(隐式表:table)=getCard()匹配{case cardpoption@Some(Card)=>table.addCard(Card)cardpoption case None=>None}
@HappyCoder-我不明白为什么你认为
getCard
不是一个额外的名字。此外,将参数传递给
()=>A
比传递给
=>A
更难。也许有理由按照你的方式去做,但“可读性更强”和“名字更少”并不在其中。谢谢!我最终通过一个函数完成了它。看起来更具可读性。给变量的名称更少
private def putOnTable(getCard:()=>Option[Card])(隐式表:table)=getCard()匹配{case cardpoption@Some(Card)=>table.addCard(Card)cardpoption case None=>None}
@HappyCoder-我不明白为什么你认为
getCard
不是一个额外的名字。此外,将参数传递给
()=>A
比传递给
=>A
更难。也许有理由按照你的方式去做,但“可读性更强”和“名字更少”并不在其中。