在 SBT 中的非穷举匹配上使编译失败 [英] Make Compile Fail on Non-Exhaustive Match in SBT

查看:31
本文介绍了在 SBT 中的非穷举匹配上使编译失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个特质,Parent,有一个孩子 Child.

Let's say that I have a trait, Parent, with one child, Child.

scala> sealed trait Parent
defined trait Parent

scala> case object Boy extends Parent
defined module Boy

我编写了一个函数,该函数在密封特征上进行模式匹配.我的 f 函数是 total,因为只有一个 Parent 实例.

I write a function that pattern matches on the sealed trait. My f function is total since there's only a single Parent instance.

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

然后,2 个月后,我决定添加 ParentGirl 孩子.

Then, 2 months later, I decide to add a Girl child of Parent.

scala> case object Girl extends Parent
defined module Girl

然后重写 f 方法,因为我们使用的是 REPL.

And then re-write the f method since we're using 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

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

If I were to encounter a non-exhaustive match, then I'd get a compile-time warning (as we see here).

但是,我怎样才能使编译失败在非详尽的比赛中?

However, how can I make the compilation fail on a non-exhaustive match?

推荐答案

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

You can add -Xfatal-warnings to Scalac's options. That way any warning will be treated as an error.

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

In sbt, you can achieve that with:

scalacOptions += "-Xfatal-warnings"

这篇关于在 SBT 中的非穷举匹配上使编译失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆