I have a mixed Scala/Java project. I'm trying to write a Scala function that would accept either Scala maps (from Scala code) or Java maps (from Java code) - java.util.HashMap for a start.
Here's what I came up with (Scala code):
def test[M <: scala.collection.Map[String, Any] with java.util.HashMap[String, Any]] (m: M): Int = { ??? }
and trying to call it from Java code like this:
HashMap m = new HashMap<String, Character>();
m.put("key", 'V');
ScalaCode.test(m);
which gives me a compile-time error:
[javac] /home/username/test/JavaCode.java:79: error: method test in class ScalaCode cannot be applied to given types;
[javac] ScalaCode.test(m);
[javac] ^
[javac] required: M
[javac] found: HashMap
[javac] reason: inferred type does not conform to declared bound(s)
[javac] inferred: HashMap
[javac] bound(s): HashMap<String,Object>,Map<String,Object>
[javac] where M is a type-variable:
[javac] M extends HashMap<String,Object>,Map<String,Object> declared in method <M>test(M)
Edit: I changed the assignment to
HashMap<String, Character> m = new HashMap<String, Character>();
trying to appease Java type inference, no luck - now it says:
[javac] reason: inferred type does not conform to declared bound(s)
[javac] inferred: HashMap<String,Character>
[javac] bound(s): HashMap<String,Object>,Map<String,Object>
Edit: Subtyping from java.util.Map does not help:
def test[M <: scala.collection.Map[String, Any] with java.util.Map[String, Any]] (m: M): Int = { ??? }
produces
[javac] reason: inferred type does not conform to declared bound(s)
[javac] inferred: HashMap<String,Character>
[javac] bound(s): scala.collection.Map<String,Object>,java.util.Map<String,Object>
What is wrong with a type bound for M?