scalagenericstypespattern-matchingunchecked-cast

How to match on unknown generic type without warnings


I have a function that might receive input of any Java/Scala type as argument:

def foo(arbitraryInput: Object): Option[Object] = {
    arbitraryInput match {
        case map: Map[Object, Object] => map.get("foo")
        // ...
        case _ => None
    }
}

I have a problem with the : Map[Object, Object]-pattern:

Is it possible to match like this and tell the compiler "hey, I know the type info is lost at runtime, Object is fine, just give me Map[Any, Any]"?


Solution

  • You can add the @unchecked annotation to some of the type arguments:

    def test(data: Any): Option[Any] = data match {
      case map: Map[Any @unchecked, _] => map.get("foo")
      case _ => None
    }