我可以强制scala错误的一个不完全的匹配? [英] Can I force scala to error on an inexhaustive match?

查看:199
本文介绍了我可以强制scala错误的一个不完全的匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不完全的匹配,例如

def foo[A](t: Seq[A]) = t match {
    Seq(x) => x
}

通常(不总是,但通常)将在运行时崩溃。 Scala警告,但在增量构建中,文件可能已经编译,所以我会错过警告。

is often (not always, but usually) a mistake on my part that will crash at runtime. Scala warns, but in an incremental build, the file might already be compiled so I will miss the warning.

有一种方法,无论是全局还是本地,注释,强制scala将警告转为错误?

Is there a way, either globally or locally, perhaps by an annotation, to force scala to turn the warning into an error?

推荐答案

可以提供一个自定义报告错误(或相反),但API目前是基于字符串的,因此它将过滤字符串消息,而不是类型的警告。

It's possible to supply a custom reporter that arbitrarily reports warnings as errors (or conversely), but the API is currently string-based, so it would filter on string messages and not typed warnings.

没有内置的方法对特定警告失败,但 -Xlint -Xfatal-warnings 是升级警告的常用方式。

There is no built-in way to fail on particular warnings, but -Xlint -Xfatal-warnings is the usual way to escalate warnings.

警告抑制已被要求,但被认为是危险的。对于致命警告,要求是抑制被认为是良性的警告。

Warning suppression has been requested, but considered dangerous. With fatal warnings, the requirement would be to suppress the warnings that are considered benign.

如果您有一个剩余的弃用,可以禁止警告-Xfatal-warnings)通过从已过时的方法调用它;如果该方法是本地方法,它不会生成警告。

If you have a residual deprecation, it's possible to suppress the warning (which would fail under -Xfatal-warnings) by invoking it from a deprecated method; if that method is local, it won't generate a warning.

scala> @deprecated("","") def f = 8
f: Int

scala> f
<console>:9: warning: method f is deprecated: 
              f
              ^
scala> object A {
     | def a = {
     | @deprecated("","") def _f = f
     | _f
     | }}
defined object A

scala> A.a
res1: Int = 8

本地弃用技巧本身已弃用,仍然使用转发随播广告:

The local deprecation trick was itself deprecated, but you can still use a forwarding companion:

scala> @deprecated("","") def f = 8
f: Int

scala> f
warning: there was one deprecation warning; re-run with -deprecation for details
res0: Int = 8

scala> @deprecated("","") class C { def g = f }; object C extends C
defined class C
defined object C

scala> C.g
res1: Int = 8

这篇关于我可以强制scala错误的一个不完全的匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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