S
S
sys_user2020-10-03 22:56:43
Java
sys_user, 2020-10-03 22:56:43

Why are functional interfaces needed in java?

Why do we need functional interfaces and what is their purpose? Everyone on google says that they are needed for lambda expressions, but functional interfaces appeared before the release of java 8

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2020-10-04
@sys_user

A functional interface is not something technical that is implemented in a language or virtual machine. It's just an abstraction that has always been in Java.
Java was conceived as a purely object-oriented language, so there were never any functions in it. All behavior resides in methods. But for event handlers, for example, you only need behavior, not state, so the "wrapper" method object is useless. Usually the handler looked like this:

someButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        someTextField.setText("Кнопка нажата");
    }
});

ActionListener has a functional interface. That is, an interface with one method, as if declaring "I'm not a class, I'm a function."
In Java 8, there were simply ways to work more conveniently with functional interfaces - lambdas appeared in the language, the virtual machine got tools to generate classes with a functional interface from lambdas, and the java.util.function package appeared in the standard library, containing a set of universal functional interfaces , which allow you to pass and return lambdas between methods in the code of different developers.

D
Denis Zagaevsky, 2020-10-04
@zagayevskiy

For lambdas, this is the correct answer.
The creators of Java did not manage (ashamed / considered unnecessary / etc) to make a separate piece of syntax for a normal description of functional types, instead they made it so that an interface can be mapped into a lambda if it (the interface) has exactly one abstract method. Actually, all these BiFunction, Predicate, ToLongBiFunction and other frills are crutches so that you can transfer lambdas somewhere. Of course, there will not be enough of them, and you will have to declare your crutches with a suitable signature.
All this was annotated with the @FunctionalInterface annotation so that the compiler could swear that you make mistakes when declaring a functional interface. Isn't it great? (No)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question