scala - -Xlint :unsound-match flag do in Scala? 是什么

标签 scala

当我看到标志 -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 _ => ()
}

这是因为 ==用于检查是否xB ,但在这种情况下,==行为非常奇怪:
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/

    相关文章:

    scala - 如何使用映射将数据框保存到Elasticsearch

    scala - 更改 build.sbt 以使 ScalaTest 测试能够与 Scala Play 一起运行

    scala - Scala 2.10.1 中的新脱糖行为

    scala - 是否可以访问 spark.ml 管道中的估算器属性?

    scala - 如何在 scala 中向迭代器追加元素

    java - 服务器端的响应式 Web 模式

    scala - SBT 挂起等待孤立子进程完成

    java - 导致堆空间用尽的可能原因是什么?是否有避免它的最佳实践?

    scala - "def"和 "val"定义函数有什么区别

    scala - 将并行集合与Akka混合