在 Scala 中同一个受保护的案例语句中存在多个条件



我有几个条件想要堆叠在scala匹配语句中。在另一种语言中,我可以省略 switch 语句大小写之间的"中断"。

我知道我可以组合由管道字符分隔的原始替代方案,但似乎找不到如何组合受保护的情况,例如:

val isAdmin = true
myval match {
  case 1 if isAdmin => ...
  case 2 if isAdmin => ...
  case 1 | 2 => // this is fine but doesn't apply the guard, so no use
  case 1 | 2 if isAdmin => // doesn't apply the guard to '1'
  case 1 if isAdmin | 2 if isAdmin => // invalid syntax
}

是否可以以某种方式合并前两种情况?

警卫声明适用于一切,无论好坏。 这意味着您的示例

  case 1 | 2 if isAdmin => ...

实际上做你想做的事,你说的不做,但这也意味着

Option("Hi") match {
  case Some(x) | None if x == "Hi" => 1
  case _ => 0
}

不起作用。 (事实上,它甚至不会编译。

幸运的是,Scala 允许你在几乎任何地方放置一个 def。

def caseNice = 1
Option("Hi") match {
  case Some(x) if x.length < 3 => caseNice
  case None => caseNice
  case _ => 0
}

这就是您应该如何处理难以从单个case语句调用的常见功能。

最新更新