无法从Scala方法返回地图

时间:2019-05-01 07:40:10

标签: scala

我正尝试通过以下scala方法返回Map。

我有两个带有一些匹配键的不同地图。我需要找到它们之间的匹配键,并从它们中选择值,然后按照我想要的方式将它们放在另一个Map中。下面是我为上述操作编写的代码。

val common      = rdKeys.keySet.intersect(bounds.keySet).toList
val metaColumns = getReadColumns(common, rdKeys, bounds)
def getReadColumns(common:List[String], rdKeys:scala.collection.mutable.Map[String, String], bounds:scala.collection.mutable.Map[String, String]): scala.collection.mutable.Map[String, String] = {
  var metaMap = scala.collection.mutable.Map[String, String]
  common.map {
    c => metaMap += (c -> bounds(c) + "|" + rdKeys(c))
  }
  metaMap
}

但是该方法给我一个编译错误:

Expression of type Seq[(String, String)] => mutable.Map[String, String] doesn't confirm to expected type mutable.Map[String, String]

所有方法参数,方法内部使用的Map和方法的返回类型均为mutable.Map [String,String]。我不明白我在这里犯了什么错误。 谁能让我知道该怎么办才能解决问题?

2 个答案:

答案 0 :(得分:4)

您遇到了错误

Expression of type Seq[(String, String)] => mutable.Map[String, String] doesn't confirm to expected type mutable.Map[String, String]

由于语句scala.collection.mutable.Map[String, String]返回函数Seq[(String, String)] => mutable.Map[String, String]

您可以通过empty方法进行更正:

      def getReadColumns( common:List[String], 
                        rdKeys:scala.collection.mutable.Map[String, String], 
                        bounds:scala.collection.mutable.Map[String, String]):scala.collection.mutable.Map[String, String] = {

      val metaMap = scala.collection.mutable.Map.empty[String, String]
      common.foreach {
        c => metaMap.update(c, bounds(c) + "|" + rdKeys(c)) 
      }
      metaMap
    }

P.S。或使用c => metaMap += c -> (bounds(c) + "|" + rdKeys(c))

答案 1 :(得分:3)

map保留集合类型。您可以将List映射到另一个List,最后将List直接投射到Map

val common = List("a", "b")
val rdKeys = Map("a" -> 1, "b" -> 1)
val bounds = Map("a" -> 10, "b" -> 10)
common // this is a list
     .map(c => c -> (bounds(c) + "|" + rdKeys(c))) // this is a list
     .toMap // then cast to it to a Map

此代码输出

scala.collection.immutable.Map[String,String] = Map(a -> 10|1, b -> 10|1)