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:

JavaScript

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.

JavaScript

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