match expression nested inside a case body of another match

ID

scala.maintainability.nested_match

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Complexity

Language

Scala

Description

Reports a match expression written inside the body of a case arm of another match.

Rationale

Nesting multiplies the number of paths through the code: the reader has to track the outer pattern that is already bound while working out which inner arm applies, and each combination needs its own test. Scala can usually express the same decision as one flat match over a tuple or a richer pattern, which is both shorter and checked for exhaustiveness by the compiler.

The following code illustrates the pattern detected by this rule:

class NestedMatch {
  def describe(a: Option[Int], b: Option[Int]): String = {
    // FLAGGED: match expression nested inside a case body of another match
    a match {
      case Some(x) =>
        b match {
          case Some(y) => s"both $x and $y"
          case None    => s"only $x"
        }
      case None => "neither"
    }
  }
}

Remediation

Match on a tuple of the two scrutinees, e.g. (a, b) match { case (Some(x), Some(y)) ⇒ …​ }, or extract the inner match into a well-named method that the outer arm calls. A for comprehension is often the clearest option when both scrutinees are Option or Either.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved