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 thatnon-variable type argument is unchecked
.If I say
case map : Map[_, _]
, I get an error onmap.get
, indicating the compiler found type_
, but was looking forObject
.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
}