Scala中密封Trait穷尽模式匹配却触发「可能非穷尽匹配」警告的原因咨询
Let's break down why you're seeing that confusing warning and how to fix it:
Root Cause 1: You're matching an undefined Rectangle type
Looking at your code, you haven't actually defined a Rectangle case class that extends Rectangular—but you've included case Rectangle(_, _, predef) in your match statement. Since Rectangle isn't a valid case class or extractor in your codebase, this pattern is completely ineffective: it will never match any Shape instance (all your existing Shape subtypes have only 2 constructor parameters, while this pattern expects 3).
Root Cause 2: Compiler exhaustiveness check gets confused
The invalid Rectangle pattern throws off Scala's exhaustiveness analyzer. Instead of recognizing that your Square and Circle cases cover all existing Shape subtypes, the compiler misinterprets the undefined Rectangle as a potential subtype of Shape. This leads to the contradictory warning that lists the very cases you've already implemented as "unmatched".
How to Fix It
You have two options depending on your intent:
Option 1: Add the missing Rectangle case class
If you meant to have a Rectangle subtype of Rectangular, define it explicitly:
case class Rectangle(width: Double, height: Double, colour: Colour) extends Rectangular
Once you add this, your match statement will correctly cover all Shape subtypes (Square, Rectangle, Circle), and the warning should disappear.
Option 2: Remove the invalid Rectangle pattern
If the Rectangle case was a typo, delete that line entirely. Your remaining matches for Square and Circle already cover all valid Shape instances (since Square is the only subtype of Rectangular, and Rectangular is sealed so no new subtypes can be added outside the file).
Alternatively, if you want to match all Rectangular instances in one case (instead of just Square), you can use a type pattern for better robustness:
case object Draws { def apply(shape: Shape): String = shape match { case r: Rectangular => r.colour.toString case Circle(_, colour) => colour.toString } }
This way, if you ever add new Rectangular subtypes later, you won't need to update the match statement for each one.
Will this actually trigger a MatchError?
In your current code, no—because the invalid Rectangle pattern never matches anything, but your Square and Circle cases do cover all valid Shape instances. The warning is a false positive caused by the undefined pattern confusing the compiler. That said, it's still important to fix the pattern match to avoid future issues (like if you do add a Rectangle later and forget to update the match).
内容的提问来源于stack exchange,提问作者Veidt

