E092: Unchecked Type Pattern

This warning is emitted when a type pattern cannot be fully checked at runtime due to type erasure.

Type arguments and type refinements are erased during compile time, making it impossible to check them at run-time. This can lead to unexpected behavior if the actual type doesn't match the pattern.


Example

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

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")
// 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")