I need to perform an add operation on two big decimals that are wrapped optionals:
Optional ordersTotal;
Optional newOrder;
<
Considering that you want to reassign to ordersTotal
, you'll notice that ordersTotal
only changes if newOrder
is present.
You can thus start with that check, and write it as:
if (newOrder.isPresent()) {
ordersTotal = newOrder.map(ordersTotal.orElse(ZERO)::add);
}
(This could be considered as a simplification of Stuart Marks' second solution. This is also a case where the method reference cannot be converted back to a lambda, due to ordersTotal
not being effectively final)
If you start by this check, there is also another possible “clever” approach:
if (newOrder.isPresent()) {
ordersTotal = ordersTotal.map(o -> newOrder.map(o::add)).orElse(newOrder);
}
where the intermediate map()
returns an Optional
whose inner Optional
cannot be empty. I wouldn't consider it a good solution due to its bad readability, and I would thus recommend the first option or one of Stuart's solutions.