我有一个混合的 Scala/Java 项目。我正在尝试编写一个 Scala 函数,该函数将接受Scala映射(来自 Scala 代码)或 Java 映射(来自 Java 代码) - 首先是 java.util.HashMap。
这是我想出的(Scala代码):
def test[M <: scala.collection.Map[String, Any] with java.util.HashMap[String, Any]] (m: M): Int = { ??? }
并尝试从 Java 代码中调用它,如下所示:
HashMap m = new HashMap<String, Character>();
m.put("key", 'V');
ScalaCode.test(m);
这给了我一个编译时错误:
[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)
编辑:我将作业更改为
HashMap<String, Character> m = new HashMap<String, Character>();
试图安抚 Java 类型推断,但没有运气 - 现在它说:
[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>
编辑:来自 java.util.Map 的子类型没有帮助:
def test[M <: scala.collection.Map[String, Any] with java.util.Map[String, Any]] (m: M): Int = { ??? }
生产
[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>
与 M 绑定的类型有什么问题?