E121: Match Case Only Null Warning — null만 매칭하는 케이스 경고
E121: Match Case Only Null Warning — null만 매칭하는 케이스 경고
패턴 매칭 케이스가 null과 그 외에는 아무것도 매칭할 수 없는 상황일 때 컴파일러가 내는 경고예요.
본문
이 경고는 패턴 매칭의 케이스가 null만 매칭할 수 있고 다른 값은 전혀 매칭할 수 없을 때 발생해요.
이런 경우는 보통 해당 케이스가 비-null 값에 대해서는 사실상 도달할 수 없는 케이스임을 뜻해요. 이미 앞선 패턴들이 모든 비-null 케이스를 덮어버렸기 때문이죠. null을 매칭하려는 의도라면, case null =>처럼 명시적으로 적어주는 게 올바른 방법이에요.
예시
def example(s: String | Int): Int = s match
case _: Int => 1
case _: String => 2
case _ => 3
에러
-- [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).
해결 방법
null 매칭이 의도된 거라면 명시적인 null 패턴으로 바꾸면 돼요.
// 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
null 매칭이 필요 없다면, 도달할 수 없는 해당 케이스만 제거하면 돼요.
// 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