private static Map<Integer, Integer> scalaIntsMapToJavaMap(scala.collection.Map<Object, Object> map) {
return (Map<Integer, Integer>) JavaConverters.mapAsJavaMapConverter(map);
}
当我在sbt中运行这个Java文件时,我得到以下异常。
Exception in thread "main" java.lang.ClassCastException: scala.collection.convert.Decorators$AsJava cannot be cast to java.util.Map
at SomeClass.scalaIntsMapToJavaMap(SomeClass.java:92)
at SomeClass.main(SomeClass.java:57)
java.lang.RuntimeException: Nonzero exit code returned from runner: 1
at scala.sys.package$.error(package.scala:27)
答案 0 :(得分:1)
谷歌搜索后我发现了这个:
private static Map<Integer, Integer> scalaIntsMapToJavaMap(scala.collection.Map<Object, Object> map) {
return (Map<Integer, Integer>) JavaConverters$.MODULE$.mapAsJavaMapConverter(map);
}
然而,更优雅的解决方案是在Scala代码中公开您的方法的Java版本。从scala代码中,您可以使用以下命令执行此操作:
import collection.JavaConverters._
val map: Map[Int, Int] = Map(1 -> 2, 2 -> 3)
def getMap(): java.collection.Map[Integer, Integer] = {
map.asJava()
}