scala - 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 .
推荐阅读
- sql - 在 SQL 中创建表时如何从生日计算年龄?
- postgresql - 在同一查询中更新 json 数据中的多个键
- c++ - 在 C++ 中使用 this-> 指针访问全局变量?
- windows - 程序 a.exe 运行失败:访问被拒绝在 line:1 char:1
- regex - Python Regex 一些名称 + 美国地址
- r - 通过R中的过滤器识别函数输入?
- android - 尝试设置状态时嵌套流生成器未更新
- sql-server - T-SQL 在一列值更改时返回该行
- python-3.x - Pandas 按天滚动时间窗口而不是单个行
- android - 如何在android中为管理员和用户实现自动登录?我的代码崩溃了