Back to Scala3

E029: Pattern Match Exhaustivity

docs/_docs/reference/error-codes/E029.md

3.8.42.2 KB
Original Source

E029: Pattern Match Exhaustivity

This warning is emitted when a pattern match expression may not handle all possible input values. The compiler detects cases that are not covered by any of the match cases.

There are several ways to make the match exhaustive:

  • Add missing cases as shown in the warning
  • If an extractor always returns Some(...), write Some[X] for its return type
  • Add a case _ => ... at the end to match all remaining cases

Example

scala
enum Color:
  case Red, Green, Blue

def describe(c: Color): String = c match
  case Color.Red => "red"
  case Color.Green => "green"

Warning

scala
-- [E029] Pattern Match Exhaustivity Warning: example.scala:4:33 ---------------
4 |def describe(c: Color): String = c match
  |                                 ^
  |                                 match may not be exhaustive.
  |
  |                                 It would fail on pattern case: Blue
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | There are several ways to make the match exhaustive:
  |  - Add missing cases as shown in the warning
  |  - If an extractor always return Some(...), write Some[X] for its return type
  |  - Add a case _ => ... at the end to match all remaining cases
   -----------------------------------------------------------------------------

Solution

scala
// Add the missing case
enum Color:
  case Red, Green, Blue

def describe(c: Color): String = c match
  case Color.Red => "red"
  case Color.Green => "green"
  case Color.Blue => "blue"
scala
// Alternative: add a wildcard case for remaining patterns
enum Color:
  case Red, Green, Blue

def describe(c: Color): String = c match
  case Color.Red => "red"
  case Color.Green => "green"
  case _ => "other"
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>