0

We have code like this:

if (defaultCategoryEntry.isPresent())
    {
      defaultCategoryEntry.get().setValue(defaultCategoryEntry.get().getValue() + amountAdjustment);
      paymentMember.setAmount(paymentMember.getFeederBuy().getAmount()); 
    }
    else
    {
        addWarning(message().masterFeederAmountDoesnotMatch("Feeder"));
    }

Can we rewrite it in functional style? The only way we found is:

defaultCategoryEntry.map(e -> 
{
e.setValue(e.getValue() + amountAdjustment);

   paymentMember.setAmount(paymentMember.getFeederBuy().getAmount()); 
return e;
).orElseGet($ ->
{
addWarning(message().masterFeederAmountDoesnotMatch("Feeder"));
return null;
});

But this is very ugly. Are there any better ways?

maxpovver
  • 1,580
  • 14
  • 25
  • 2
    Just as a note, this use case is explicitly [_not_ what Optional was designed for](http://stackoverflow.com/a/26328555/1076640). So, if it feels like there's no natural/nice way to get Optional to work how you want, that could be why. – yshavit Jan 27 '16 at 15:53
  • 1
    @yshavit: I don’t see where this use case counteracts the design intention. Actually, the OP is just asking for [`ifPresentOrElse`](http://download.java.net/jdk9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable-) which will be available not until Java 9, unfortunately. – Holger Jan 27 '16 at 18:27

0 Answers0