SBT 中的非详尽匹配导致编译失败

问题描述 投票:0回答:4

假设我有一个特质,父母,有一个孩子,孩子。

scala> sealed trait Parent
defined trait Parent

scala> case object Boy extends Parent
defined module Boy

我编写了一个与密封特征进行模式匹配的函数。我的

f
函数是 total,因为只有一个
Parent
实例。

scala> def f(p: Parent): Boolean = p match { 
     |   case Boy => true
     | }
f: (p: Parent)Boolean

然后,2 个月后,我决定添加

Girl
Parent
孩子。

scala> case object Girl extends Parent
defined module Girl

然后重写

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

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

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

scala pattern-matching sbt
4个回答
13
投票

您可以将

-Xfatal-warnings
添加到 Scalac 的选项中。这样任何警告都会被视为错误。

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

scalacOptions += "-Xfatal-warnings"

8
投票

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

scalacOptions += "-Wconf:cat=other-match-analysis:error"

Lukas Rytz 的详细操作方法。


0
投票

编译器标志仅适用于 Scala 3:

scalacOptions += "-Ycheck-all-patmat"

更多


-7
投票

也许您可以放入默认情况来捕获后定义的元素并将其绑定到您可以单独管理的部分函数。然后该部分将充当“默认处理程序”。

  sealed trait Animal
  case class Dog(name: String) extends Animal
  case class Cat(name: String) extends Animal

  val t: Animal = Dog("fido")

  // updates when the trait updates
  val partial = PartialFunction[Animal, Unit] {
    case Dog(_) => println("default dog")
    case Cat(_) => println("default cat")
    case _ => throw new RuntimeException("Broken")
  }

  // matches that may be out of date refer to it
  t match {
    case Dog(_) => println("specific dog")
    case t => partial(t)
  }

或者也许您可以一直使用 PartialFunctions 并将它们链接在一起。

© www.soinside.com 2019 - 2024. All rights reserved.