我试图写一个函数
def convert(x: String): String = ...
通过在地图中查找来转换其参数,如果参数不是地图中的键,则返回x
。不幸的是,必须通过调用返回原始Map
:
public static Map getMapFromConfiguration() { ... }
这是我无能为力的遗留代码。在这种特殊情况下,返回的映射的键和值将为String
(如果密钥或值具有其他类型,则代码抛出异常时可以正常)。到目前为止,我能够获得编译代码的唯一方法是构建一个新的Map[String,String]
:
def convert(x: String): String = {
val mapFromConfig: scala.collection.mutable.Map[_,_] = JavaClass.getMapFromConfiguration().asScala
val convertedMap: Map[String,String] = (mapFromConfig map {
case (key, value) => key.asInstanceOf[String] -> value.asInstanceOf[String] }).toMap
convertedMap.getOrElse(x, x)
}
我已尝试过各种方法直接在get
上使用getOrElse
或mapFromConfig
,但却找不到任何可编译的内容。一些尝试:
val mapFromConfig: scala.collection.mutable.Map[_ <: Any, _ <: Any] = JavaClass.getMapFromConfiguration().asScala
mapFromConfig.getOrElse(x, x).asInstanceOf[String]
Type mismtach, expected: _$1, actual: String
val mapFromConfig: scala.collection.mutable.Map[Any,Any] = JavaClass.getMapFromConfiguration().asScala
mapFromConfig.getOrElse(x, x).asInstanceOf[String]
error: type mismatch;
found : scala.collection.mutable.Map[?0,?1] where type ?1, type ?0
required: scala.collection.mutable.Map[Any,Any]
Note: ?0 <: Any, but trait Map is invariant in type A.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
Note: ?1 <: Any, but trait Map is invariant in type B.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
val mapFromConfig: java.util.Map[_,_] = JavaClass.getMapFromConfiguration()
mapFromConfig.getOrDefault(x, x).asInstanceOf[String]
Type mismtach, expected: _$2, actual: String
有没有一种很好的方法可以在不创建中间地图的情况下完成我的需要?
答案 0 :(得分:1)
主要技巧是将非通用Map
强制转换为显式通用java.util.Map[String, String]
。适用于我的代码是
val map: java.util.Map[String, String] = ScalaToJava.getMapFromConfiguration.asInstanceOf[java.util.Map[String, String]]
println(map.get("key"))
给定Java代码:
public class ScalaToJava {
static Map getMapFromConfiguration() {
HashMap map = new HashMap();
map.put("key", "value");
return map;
}
}
或者,如果您想将map
转换为Scala,可以使用类似
val map = ScalaToJava.getMapFromConfiguration.asInstanceOf[java.util.Map[String, String]].asScala
println(map.get("key"))