Naseebullah Safi - 18 days ago 7
Scala Question

# How to add List of Option of doubles in scala

I have a list of option like so,

``````var data = List(
List(Some(313.062468), Some(27.847252)),
List(Some(301.873641), Some(42.884065)),
List(Some(332.373186), Some(53.509768))
)
``````

And I'd like to sum all the values of each nested list.

I have the following code which doesn't work:

``````return data.flatten.foldLeft((Some(0), Some(0))) {
case ((accA, accB), (a, b)) => {
(_ + a, _ + b)
}
}
``````

# Flatten, Collect and Sum

Flatten, collect and sum

``````data.flatten.collect { case Some(value) => value }.sum
``````

Scala REPL

``````scala> var data = List(
|   List(Some(313.062468), Some(27.847252)),
|   List(Some(301.873641), Some(42.884065)),
|   List(Some(332.373186), Some(53.509768))
| )
data: List[List[Some[Double]]] = List(List(Some(313.062468), Some(27.847252)), List(Some(301.873641), Some(42.884065)), List(Some(332.373186), Some(53.509768)))

scala>

scala> data.flatten
res2: List[Some[Double]] = List(Some(313.062468), Some(27.847252), Some(301.873641), Some(42.884065), Some(332.373186), Some(53.509768))

scala> data.flatten.collect { case Some(value) => value }.sum
res3: Double = 1071.55038
``````

# Option is iterable

Looks quite neat.

``````data.iterator.flatMap(_.iterator.flatMap(_.iterator)).sum
``````

Scala REPL

``````scala> data.iterator.flatMap(_.iterator.flatMap(_.iterator)).sum
res5: Double = 1071.55038
``````