Match expression on Int is not exhaustive
Asked Answered
W

2

6

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?

Wershba answered 1/4, 2021 at 10:18 Comment(1)
It does ... With appropriate optionsMauceri
A
8

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.

Antiquated answered 1/4, 2021 at 11:0 Comment(0)
P
3

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.

Pinette answered 1/4, 2021 at 10:45 Comment(1)
Could you please provide an example? So other persons who will face same issue will get solutionWershba

© 2022 - 2024 — McMap. All rights reserved.