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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With