E029: Pattern Match Exhaustivity — 패턴 매치가 빠짐없이 처리되는지 확인해요
E029: Pattern Match Exhaustivity — 패턴 매치가 빠짐없이 처리되는지 확인해요
패턴 매치(pattern match) 식이 가능한 모든 입력 값을 처리하지 못할 수 있을 때 이 경고(warning) 가 나와요. 컴파일러가 어떤 match 케이스로도 덮이지 않는 경우를 감지한 거예요.
본문
match를 완전(exhaustive)하게 만드는 방법은 몇 가지가 있어요.
- 경고에 표시된 대로 빠진 케이스를 추가한다
- extractor가 항상
Some(...)을 돌려준다면, 반환 타입을Some[X]로 써준다 - 마지막에
case _ => ...를 추가해서 나머지 케이스를 모두 처리한다
예제 (Example)
enum Color:
case Red, Green, Blue
def describe(c: Color): String = c match
case Color.Red => "red"
case Color.Green => "green"
Color는 Red, Green, Blue 세 값을 갖는데, describe는 Red와 Green만 처리하고 있어요. Blue가 들어오면 처리할 케이스가 없죠.
경고 메시지 (Warning)
-- [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)
빠진 케이스를 추가하거나, 나머지 패턴을 처리하는 와일드카드 케이스를 추가하면 돼요.
// 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"
// 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"