Int 上的匹配表达式并不详尽
Match expression on Int is not exhaustive
我开始学习 Scala。
我很惊讶下一个代码编译:
object Hello extends App {
def isOne(num: Int) = num match {
case 1 => "hello"
}
}
例如,您不能在 Rust 中做类似的事情。
为什么 Scala 编译器不强制我为 case
提供默认值?
我会说它有点不安全。
是否有任何 Scala linter 或其他东西?也许有些旗帜?
嗯,你可以在结构匹配上稍微处理一下,通过设置
scalac 设置中的“-Xfatal-warnings”选项,这会将此警告和其他警告提升为错误。
因为 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
If the selector of a pattern match is an instance of a sealed class,
the compilation of pattern matching can emit warnings which diagnose
that a given set of patterns is not exhaustive, i.e. that there is a
possibility of a MatchError being raised at run-time.
我开始学习 Scala。
我很惊讶下一个代码编译:
object Hello extends App {
def isOne(num: Int) = num match {
case 1 => "hello"
}
}
例如,您不能在 Rust 中做类似的事情。
为什么 Scala 编译器不强制我为 case
提供默认值?
我会说它有点不安全。
是否有任何 Scala linter 或其他东西?也许有些旗帜?
嗯,你可以在结构匹配上稍微处理一下,通过设置 scalac 设置中的“-Xfatal-warnings”选项,这会将此警告和其他警告提升为错误。
因为 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
If the selector of a pattern match is an instance of a sealed class, the compilation of pattern matching can emit warnings which diagnose that a given set of patterns is not exhaustive, i.e. that there is a possibility of a MatchError being raised at run-time.