当我看到标志 -Xlint:unsound-match
时,我正在寻找在 Scala 中使非穷举匹配成为编译错误的方法。 .然而,我找不到太多关于它的信息,我发现的一个例子在有和没有标志的情况下工作相同,所以我真的不知道什么时候会有帮助。有人可以解释它和/或提供在没有此标志的情况下编译时没有警告的匹配示例,但会生成警告吗?
最佳答案
以下程序编译得很好,但在运行时因 ClassCastException 而崩溃:
case class A()
object B extends A() {
def bar() = println("only B has this method")
}
A() match {
case x @ B => x.bar()
case _ => ()
}
这是因为
==
用于检查是否x
是 B
,但在这种情况下,==
行为非常奇怪:case class A()
object B extends A()
B == A() // returns true, because extending from case classes is evil.
这似乎是因为
B
继承了equals
从案例类,所以B == a
所有 a: A
,但同时 a: B.type
几乎所有 a: A
都是假的(除了 B
本身)。 使用
-Xlint:unsound-match
编译时在较旧的 scalac 版本(例如 2.15)上,代码会产生以下警告: warning: The value matched by $anon.this.B is bound to x, which may be used under the
unsound assumption that it has type this.B.type, whereas we can only safely
count on it having type this.A, as the pattern is matched using `==` (see scala/bug#1503).
case x @ B => x.bar()
^
one warning found
而没有
-Xlint
, 没发生什么事。请注意
-Xlint:unsound-match
似乎已在更新版本的编译器中删除(至少我在最近的提交中找不到它),因此,显然,它现在根本没有做任何事情。
关于scala - -Xlint :unsound-match flag do in Scala? 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56480799/