Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Compile Fail on Non-Exhaustive Match in SBT

Let's say that I have a trait, Parent, with one child, Child.

scala> sealed trait Parent
defined trait Parent

scala> case object Boy extends Parent
defined module Boy

I write a function that pattern matches on the sealed trait. My f function is total since there's only a single Parent instance.

scala> def f(p: Parent): Boolean = p match { 
     |   case Boy => true
     | }
f: (p: Parent)Boolean

Then, 2 months later, I decide to add a Girl child of Parent.

scala> case object Girl extends Parent
defined module Girl

And then re-write the f method since we're using REPL.

scala> def f(p: Parent): Boolean = p match { 
     |   case Boy => true
     | }
<console>:10: warning: match may not be exhaustive.
It would fail on the following input: Girl
       def f(p: Parent): Boolean = p match { 
                                   ^
f: (p: Parent)Boolean

If I were to encounter a non-exhaustive match, then I'd get a compile-time warning (as we see here).

However, how can I make the compilation fail on a non-exhaustive match?

like image 278
Kevin Meredith Avatar asked Feb 04 '15 17:02

Kevin Meredith


2 Answers

You can add -Xfatal-warnings to Scalac's options. That way any warning will be treated as an error.

In sbt, you can achieve that with:

scalacOptions += "-Xfatal-warnings"
like image 81
Kim Stebel Avatar answered Nov 07 '22 07:11

Kim Stebel


Since scalac 2.13.2 there's a fairly granular control of warnings. To get what OP asks:

scalacOptions += "-Wconf:cat=other-match-analysis:error"

Detailed howto by Lukas Rytz.

like image 7
Ales Kozumplik Avatar answered Nov 07 '22 07:11

Ales Kozumplik