首页 > 解决方案 > Int 上的匹配表达式并不详尽

问题描述

我已经开始学习 Scala。

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

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

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

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

我会说这有点不安全。

有没有scala linter或其他东西?也许一些标志?

标签: scalacompiler-errorspattern-matchingnon-exhaustive-patterns

解决方案


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 .


推荐阅读