Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match expression on Int is not exhaustive

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?

like image 941
captain-yossarian Avatar asked Apr 01 '21 10:04

captain-yossarian


2 Answers

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.

like image 99
Mario Galic Avatar answered Oct 19 '22 20:10

Mario Galic


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.

like image 3
Iva Kam Avatar answered Oct 19 '22 20:10

Iva Kam