Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, how can i declare a variable inside an if lambda condition?

In my code, i have a predicate method that returns i if certain conditions are met, and i need to declare a variable inside it, but the method is written in lambda, and i don't know how to do this. Here's my code:

public static Predicate<MFDWHDealExt> isAccepted() {
        MyCalendar startDate = new MyCalendar();

        return (i -> 
                i.getCompany().equals("ACCEPTED")
                && i.getDealType() == MFDealTypeEnum.AcceptedDeal              
                && i.getSettlementDate().beforeOrEqual(startDate.findDay(i.getDealDate(), 2, true))
                );
    }

i need to declare startDate (a custom date MyDate) with the value of i.getSettlementDate, otherwise the method findDay(that returns working days), because right now is null.

like image 619
R.S. Avatar asked Dec 11 '22 03:12

R.S.


1 Answers

Here:

    return (i -> { 
            return i.getCompany().equals("ACCEPTED")
              && i.getDealType() == MFDealTypeEnum.AcceptedDeal              
              && i.getSettlementDate().beforeOrEqual(startDate.findDay(i.getDealDate(), 2, true))
            });

When not using the one line syntax of lambdas, like x-> 2*x, you need block braces. And you can't use that one-line syntax when you intend to declare a local variable.

See here for the official documentation!

In other words: when you want to write several statements, like actually defining a local variable, then you need these braces!

Finally: be careful what you do here. (imho) Lambda expressions should be really short and concise. When they become "more complicated" (like: they need local variables), then I suggest to not use a lambda, but to declare a real method and call that.

like image 191
GhostCat Avatar answered May 23 '23 20:05

GhostCat