Answer the question
In order to leave comments, you need to log in
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
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("Кнопка нажата");
}
});
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 questionAsk a Question
731 491 924 answers to any question