-Xlint:unsound-match标志在Scala中做什么?

Dan*_*ral 8 scala

看到标志时,我正在寻找使非穷举匹配成为Scala中的编译错误的方法-Xlint:unsound-match。但是,我找不到很多信息,发现的一个示例在带有和不带有标志的情况下均相同,因此我真的不知道何时会有所帮助。有人可以解释它和/或提供一个在没有此标志的情况下在没有警告的情况下进行编译但会产生警告的匹配示例吗?

And*_*kin 7

以下程序可以很好地编译,但是在运行时会因ClassCastException崩溃:

case class A()
object B extends A() {
  def bar() = println("only B has this method")
}

A() match {
  case x @ B => x.bar()
  case _ => ()
}
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为==用于检查是否xB,但是在这种情况下,==其行为非常奇怪:

case class A()
object B extends A()
B == A() // returns true, because extending from case classes is evil.
Run Code Online (Sandbox Code Playgroud)

这似乎是因为B继承equals了case类,所以

  • 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
Run Code Online (Sandbox Code Playgroud)

没有它-Xlint,什么也不会发生。

请注意,-Xlint:unsound-match似乎已在较新版本的编译器中删除(至少在最近的提交中找不到),因此,显然,它现在什么也不做。