I am trying to use the fold function on Lists that contain elements of different types. Here's a simplified version of my code:
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")))
I am expecting the result
will be a List of Integer:
List(4, 4, 4, 4)
However, the error that I got were Type Mismatch for:
x : Required: List[Int], Found: Iterable[Any] with Partial Function[Int with String, Int] with Equals
"a": Required: Int with String, Found String
CodePudding user response:
fold don't do what you think. For this kind of problem, Scala standard Library Documentation is your friend : https://www.scala-lang.org/api/2.13.3/index.html
def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1
Folds the elements of this collection using the specified associative binary operator.
You need foldLeft instead
def foldLeft[B](z: B)(op: (B, A) => B): B
Applies a binary operator to a start value and all elements of this sequence, going left to right.
Note: will not terminate for infinite-sized collections.
in your case
val result = listOfMap.foldLeft(list)((x, y) => addN(x, y("a")))
//List(4, 4, 4, 4): scala.collection.immutable.List[scala.Int]