Home > database >  How to match on unknown generic type without warnings
How to match on unknown generic type without warnings

Time:10-23

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:

  • If I say case map : Map[Object, Object], I get a warning that non-variable type argument is unchecked.

  • If I say case map : Map[_, _], I get an error on map.get, indicating the compiler found type _, but was looking for Object.

  • If I say case map : Map the compiler complains that Map needs type arguments

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]"?

CodePudding user response:

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
}

  • Related