타입 패턴을 검사할 수 없어요

타입 패턴을 검사할 수 없어요 (E092: Unchecked Type Pattern)

타입 패턴이 타입 소거(type erasure) 때문에 런타임에 완전히 검사되지 못할 때 이 경고가 나요. 타입 인자와 타입 세밀화(type refinement)는 컴파일 타임에 소거되어 런타임에 검사할 수 없어요.

출처: Scala 3 Reference

본문

타입 패턴이 타입 소거로 인해 런타임에 완전히 검사될 수 없을 때 이 경고(warning)가 발생해요.

타입 인자와 타입 세밀화는 컴파일 타임에 소거되기 때문에 런타임에는 검사가 불가능해요. 실제 타입이 패턴과 맞지 않으면 예상치 못한 동작으로 이어질 수 있죠.

예시 (Example)

def example(x: Any): Unit = x match
  case list: List[String] => println("strings")
  case _ => println("other")

런타임에 List인지는 알 수 있어도 그 안의 원소가 String인지는 소거 때문에 확인할 수 없어요.

에러 (Error)

-- [E092] Pattern Match Unchecked Warning: example.scala:2:7 -------------------
2 |  case list: List[String] => println("strings")
  |       ^
  |the type test for List[String] cannot be checked at runtime because its type arguments can't be determined from Any
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Type arguments and type refinements are erased during compile time, thus it's
  | impossible to check them at run-time.
  |
  | You can either replace the type arguments by _ or use `@unchecked`.
   -----------------------------------------------------------------------------

해결 방법 (Solution)

타입 인자에 와일드카드를 써서 검사 범위를 조정할 수 있어요.

// Use a wildcard for the type argument
def example(x: Any): Unit = x match
  case list: List[?] => println("some list")
  case _ => println("other")

타입이 확실하다면 @unchecked를 쓰는 방법도 있어요.

// Or use @unchecked if you're certain about the type
import scala.unchecked
def example(x: Any): Unit = x match
  case list: List[String @unchecked] => println("strings")
  case _ => println("other")

아니면 원소 타입을 명시적으로 직접 검사해도 돼요.

// Or check the element types explicitly
def example(x: Any): Unit = x match
  case list: List[?] if list.forall(_.isInstanceOf[String]) =>
    println("strings")
  case _ => println("other")