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.

一般来说,根据Pattern Matching Expressions

如果模式匹配的选择器是一个密封类的实例, 模式匹配的编译可以发出诊断警告 一组给定的模式不是详尽无遗的,即有一个 在运行时引发 MatchError 的可能性。

,

好吧,你可以在结构匹配上稍微处理一下,通过设置 scalac 设置中的“-Xfatal-warnings”选项,这会将这个和其他警告解除为错误。