Search code examples
javalambda

Java statement before lambda


I had this code previously which worked

private Runnable persist(Data data) {
    data.setComparisonTime(NO_COMPARISON_PERFORMED);
    return () -> {
        ...
    };
}

Later I refactored the code as I'd missed this before.

private Runnable persist(Data data) { 
    return () -> {
        data.setComparisonTime(NO_COMPARISON_PERFORMED);
        ...
    };
}

What is the difference between these two statements?


Solution

  • It matters for when the data.setComparisonTime is run. You have a function that returns a function; in the first case, the setComparisonTime will be run when the persist method is run. In the latter, it will not be run until the returned lambda is run.