有没有办法在 Scala 中抑制*仅*详尽检查?

问题描述

我发现自己经常写这样的代码


thing match {
   case Case1 ...
   case Case2 ...
   case _ => throw new IllegalStateException(s"unexpected $thing")
}

有时我希望在情况不匹配时出现运行时错误。案例是断言的一种形式。

有没有更好的方法来抑制穷举检查?

我不想使用 [@unchecked](https://www.scala-lang.org/api/2.12.1/scala/unchecked.html),因为这也会禁用可达性检查,而我确实想要这样做。

解决方法

您可以使用 nowarn 注释隐藏警告:

import scala.annotation.nowarn

@nowarn("msg=not.*?exhaustive")
val r = thing match {
   case Case1 ...
   case Case2 ...
}

它是在 Scala 2.13.2 中添加的,因此如果您使用的是旧版本,则需要使用 silencer 插件。

或者,使用消音器插件,您可以设置 global regex-based suppresion