gpt4 book ai didi

scala - 无法从 Scala 方法返回 Map

转载 作者:行者123 更新时间:2023-12-01 21:57:15 25 4
gpt4 key购买 nike

我正在尝试从 scala 方法返回一个 Map,如下所示。

我有两个不同的 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]

所有的方法参数,方法内部使用的Maps以及方法的返回类型都是mutable.Map[String, String]。我不明白我在这里犯了什么错误。任何人都可以让我知道我必须做些什么来解决这个问题吗?

最佳答案

你得到了错误

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
}

附言或者使用 c => metaMap += c -> (bounds(c) + "|"+ rdKeys(c))

关于scala - 无法从 Scala 方法返回 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55933022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com