Skip to content
Advertisement

Java 8 lambda (from javascript example)

I’m learning java from javascript background, and I wonder is it possible to write similar function in Java. Here is an example in javascript:

function getBalance(side, date) {
    let balance;
    let getPrice = (f) => {
        while ((result = f(date)) == 0) {
            date++;
        }
        return result;
    }
    if (side) {
        let price = getPrice(getPrice1);
        // Some calculations
        return balance;
    } else {
        let price = getPrice(getPrice2);
        // Some calculations
        return balance;
    }
}

Where getPrice1 and getPrice2 are previously defined functions. Use of calbacks here helps to keep code short. Im not sure is it possible in Java to pass function as argument without declaring additional interfaces.

I asked this question because it is a simplified example of a real task that I encountered. What do you think will be the most elegant solution?

P.S. Looks like Functional Interfaces is the way here.

Advertisement

Answer

Yes, it’s possible.

Here’s a dummy showcase just to illustrate how things can be put together.

class Showcase {

    public static void main(String[] args) {
        Function<Function<LocalDate, Double>, Double> getPrice = f -> {
            // an example how to call it - replace it with your logic
            f.apply(LocalDate.now());

            return 0.;
        };

        getPrice.apply(Showcase::getPrice1);
        getPrice.apply(Showcase::getPrice2);
    }

    public static Double getPrice1(LocalDate date) {
        return 0.;
    }

    public static Double getPrice2(LocalDate date) {
        return 1.;
    }

}

It would be more verbose because of the typing discipline. However, the idea is fundamentally the same.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement