Back to Scala3

E121: Match Case Only Null Warning

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

3.8.41.4 KB
Original Source

E121: Match Case Only Null Warning

This warning is emitted when a pattern match case can only match null and nothing else.

This typically indicates a case that is effectively unreachable for non-null values because all non-null cases have already been covered by previous patterns. If matching null is intentional, it should be written explicitly as case null =>.


Example

scala
def example(s: String | Int): Int = s match
  case _: Int => 1
  case _: String => 2
  case _ => 3

Error

scala
-- [E121] Pattern Match Warning: example.scala:4:7 -----------------------------
4 |  case _ => 3
  |       ^
  |Unreachable case except for null (if this is intentional, consider writing case null => instead).

Solution

scala
// Use explicit null pattern if matching null is intentional
def example(s: String | Int): Int = s match
  case _: Int => 1
  case _: String => 2
  case null => 3
scala
// Or remove the unreachable case if null matching is not needed
def example(s: String | Int): Int = s match
  case _: Int => 1
  case _: String => 2
<!-- 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>