Whats the most elegant way to add two numbers that are Optional

后端 未结 8 831
既然无缘
既然无缘 2021-02-08 03:29

I need to perform an add operation on two big decimals that are wrapped optionals:

Optional ordersTotal;
Optional newOrder;
<         


        
8条回答
  •  青春惊慌失措
    2021-02-08 04:01

    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.

提交回复
热议问题