Int上的匹配表达式并不详尽

我已经开始学习 Scala。

我很惊讶下一个代码编译:

object Hello extends App {
  def isOne(num: Int) = num match {
    case 1 => "hello"
  }
}

例如,你不能在 Rust 中做类似的事情。

为什么 Scala 编译器不强制我为 提供默认值case

我会说它有点不安全。

是否有任何 Scala linter 或其他东西?也许一些标志?

回答

自Scala 2.13.4以来,对未密封类型的穷举性检查进行了改进,例如Int尝试使用编译器标志

-Xlint:strict-unsealed-patmat

例如

scala -Xlint:strict-unsealed-patmat -Xfatal-warnings
Welcome to Scala 2.13.5 (OpenJDK 64-Bit Server VM, Java 1.8.0_275).
Type in expressions for evaluation. Or try :help.

scala> def isOne(num: Int) = num match {
     |     case 1 => "hello"
     |   }
                             ^
       warning: match may not be exhaustive.
       It would fail on the following input: (x: Int forSome x not in 1)
error: No warnings can be incurred under -Werror.

但总的来说,根据模式匹配表达式

如果模式匹配的选择器是密封类的实例,则模式匹配的编译会发出警告,诊断给定的模式集并非详尽无遗,即有可能在运行时引发 MatchError .


以上是Int上的匹配表达式并不详尽的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>