Can anyone help this Scala newbie? Previously, we summed a number of quantities in a list of entities with those quantities with:
sum = entities.foldLeft(0.0)(_ + _.quantity)
Now the quantity is an Option[Double]
, and so is the sum. How can I convert this using idiomatic Scala?
If any entity's quantity is None
then the sum should also be None
.
Otherwise the sum should be Some(total)
.
Edit: Putting this thing into a unit test so that I can try all your answers out. Please note that I do need the result to be None if any quantity is None, because missing quantities mean we haven't finished yet, so the total should reflect this. Even if you don't get the right answer, if you help lead me or others to it, or help me learn something new, I'll upvote.
Edit: @sepp2k wins for a working solution plus explanation. Thanks to all for the learning!