gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:49:16 24 4
gpt4 key购买 nike

我已经开始学习Scala。
我很惊讶下一个代码会编译:

object Hello extends App {
def isOne(num: Int) = num match {
case 1 => "hello"
}
}
例如,您不能在Rust中做类似的事情。
为什么Scala编译器不强制我为 case提供默认值?
我会说这有点不安全。
是否有斯卡拉棉短绒或其他东西?也许有些标志?

最佳答案

由于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 diagnosethat a given set of patterns is not exhaustive, i.e. that there is apossibility of a MatchError being raised at run-time.

关于scala - Int上的匹配表达式并不详尽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66902676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com