SBT中非穷举匹配使编译失败

Kev*_*ith 20 scala pattern-matching sbt

让我们说我有一个特点,父母,有一个孩子,孩子.

scala> sealed trait Parent
defined trait Parent

scala> case object Boy extends Parent
defined module Boy
Run Code Online (Sandbox Code Playgroud)

我写了一个函数,模式匹配密封的特征.我的f功能是完全的,因为只有一个Parent实例.

scala> def f(p: Parent): Boolean = p match { 
     |   case Boy => true
     | }
f: (p: Parent)Boolean
Run Code Online (Sandbox Code Playgroud)

然后,2个月后,我决定添加一个Girl孩子Parent.

scala> case object Girl extends Parent
defined module Girl
Run Code Online (Sandbox Code Playgroud)

然后重新编写f方法,因为我们正在使用REPL.

scala> def f(p: Parent): Boolean = p match { 
     |   case Boy => true
     | }
<console>:10: warning: match may not be exhaustive.
It would fail on the following input: Girl
       def f(p: Parent): Boolean = p match { 
                                   ^
f: (p: Parent)Boolean
Run Code Online (Sandbox Code Playgroud)

如果我遇到一个非详尽的匹配,那么我会收到一个编译时警告(正如我们在这里看到的).

但是,如何在非详尽匹配中使编译失败

Kim*_*bel 13

您可以添加-Xfatal-warningsScalac的选项.这样任何警告都将被视为错误.

在sbt中,您可以通过以下方式实现:

scalacOptions += "-Xfatal-warnings"
Run Code Online (Sandbox Code Playgroud)

  • 这在技术上回答了这个问题,但它通常不是一个可行的解决方案.我个人有兴趣看到不需要在所有警告上失败的答案,即使它们更加混乱. (13认同)
  • @KevinMeredith当您正在进行的项目中,有很多您不关心的警告时。 (2认同)

小智 9

从 scalac 2.13.2 开始,对警告进行了相当精细的控制。为了得到OP的要求:

scalacOptions += "-Wconf:cat=other-match-analysis:error"
Run Code Online (Sandbox Code Playgroud)

Lukas Rytz 的详细操作指南。