在 HashMap 列表和 return Scala 中的另一种类型的列表上应用折叠函数

Applying fold function on a List of HashMap and return a List of another type in Scala

我正在尝试对包含不同类型元素的列表使用折叠功能。 这是我的代码的简化版本:

val list: List[Int] = List(1, 1, 1, 1)
val listOfMap: List[Map[String, Int]]= List(Map("a" -> 1), Map("a" -> 2))

def addN(list: List[Int], n: Int) = list.map(_+n)

val result = listOfMap.fold(list)((x, y) => addN(x, y("a")))

我希望 result 将是一个整数列表:

List(4, 4, 4, 4)

但是,我得到的错误是类型不匹配:

x:需要:List[Int],找到:Iterable[Any] with Partial Function[Int with String, Int] with Equals

"a":必需:带字符串的整数,找到的字符串

fold 不要按照你的想法去做。 对于此类问题,Scala 标准库文档是您的朋友:https://www.scala-lang.org/api/2.13.3/index.html

def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1

使用指定的关联二元运算符折叠此集合的元素。

你需要 foldLeft 来代替

def foldLeft[B](z: B)(op: (B, A) => B): B

将二元运算符应用于起始值和此序列的所有元素,从左到右。

注意:不会终止 infinite-sized 个集合。

你的情况

val result = listOfMap.foldLeft(list)((x, y) => addN(x, y("a")))
//List(4, 4, 4, 4): scala.collection.immutable.List[scala.Int]