Reputation: 33041
I've started learning Scala.
I was surprised that next code compiles:
object Hello extends App {
def isOne(num: Int) = num match {
case 1 => "hello"
}
}
You can't do something similar in Rust for example.
Why Scala compiler does not force me to provide default value for case
?
I'd say that it is a little bit unsafe.
Is there any scala linter or something else? Maybe some flags?
Upvotes: 6
Views: 716
Reputation: 48400
Since Scala 2.13.4 there were improvement to exhaustivity checking of unsealed types such as Int
so try with compiler flag
-Xlint:strict-unsealed-patmat
for example
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.
In general though, according to 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.
Upvotes: 8
Reputation: 962
Well you can deal with it a bit on structural matching, by setting "-Xfatal-warnings" option in scalac settings, this will lift this and other warnings to errors.
Upvotes: 3