在Scala中重新使用守卫

fom*_*mil 16 scala

我经常发现自己想要在scala中重用警卫评估的结果,例如

blah match {
  case Blah(a, b) if expensive(a) < 10 =>
     expensive(a)
  case _ => b
}
Run Code Online (Sandbox Code Playgroud)

这可能是使用一些鲜为人知的咒语吗?(放在@上面expensive不起作用)

这可能很快就会实现吗?

axe*_*l22 18

您可以使用自定义提取器执行类似操作.这应该工作:

case class Blah(a: Int, b: Int)

object expensive {
  def unapply(x: Int): Option[Double] = Some(math.cos(x))
}

Blah(1, 1) match {
  case Blah(a @ expensive(e), b) if e < 10 => println(a, b, e)
  case _ => println("nothing")
}
Run Code Online (Sandbox Code Playgroud)

确保expensive创建Option对象真的更贵,这就是上面所做的.