What are functional interfaces used for in Java 8? - java
I came across a new term in Java 8: "functional interface". I could only find one use of it while working with lambda expressions.
Java 8 provides some built-in functional interfaces and if we want to define any functional interface then we can make use of the #FunctionalInterface annotation. It will allow us to declare only a single method in the interface.
For example:
#FunctionalInterface
interface MathOperation {
int operation(int a, int b);
}
How useful it is in Java 8 other than just working with lambda expressions?
(The question here is different from the one I asked. It is asking why we need functional interfaces while working with lambda expressions. My question is: What are the other uses of functional interfaces besides use with lambda expressions?)
#FunctionalInterface annotation is useful for compilation time checking of your code. You cannot have more than one method besides static, default and abstract methods that override methods in Object in your #FunctionalInterface or any other interface used as a functional interface.
But you can use lambdas without this annotation as well as you can override methods without #Override annotation.
From docs
a functional interface has exactly one abstract method. Since default
methods have an implementation, they are not abstract. If an interface
declares an abstract method overriding one of the public methods of
java.lang.Object, that also does not count toward the interface's
abstract method count since any implementation of the interface will
have an implementation from java.lang.Object or elsewhere
This can be used in lambda expression:
public interface Foo {
public void doSomething();
}
This cannot be used in lambda expression:
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
But this will give compilation error:
#FunctionalInterface
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
Invalid '#FunctionalInterface' annotation; Foo is not a functional
interface
The documentation makes indeed a difference between the purpose
An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.
and the use case
Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
whose wording does not preclude other use cases in general. Since the primary purpose is to indicate a functional interface, your actual question boils down to “Are there other use cases for functional interfaces other than lambda expressions and method/constructor references?”
Since functional interface is a Java language construct defined by the Java Language Specification, only that specification can answer that question:
JLS §9.8. Functional Interfaces:
…
In addition to the usual process of creating an interface instance by declaring and instantiating a class (§15.9), instances of functional interfaces can be created with method reference expressions and lambda expressions (§15.13, §15.27).
So the Java Language Specification doesn’t say otherwise, the only use case mentioned in that section is that of creating interface instances with method reference expressions and lambda expressions. (This includes constructor references as they are noted as one form of method reference expression in the specification).
So in one sentence, no, there is no other use case for it in Java 8.
As others have said, a functional interface is an interface which exposes one method. It may have more than one method, but all of the others must have a default implementation. The reason it's called a "functional interface" is because it effectively acts as a function. Since you can pass interfaces as parameters, it means that functions are now "first-class citizens" like in functional programming languages. This has many benefits, and you'll see them quite a lot when using the Stream API. Of course, lambda expressions are the main obvious use for them.
Not at all. Lambda expressions are the one and only point of that annotation.
A lambda expression can be assigned to a functional interface type, but so can method references, and anonymous classes.
One nice thing about the specific functional interfaces in java.util.function is that they can be composed to create new functions (like Function.andThen and Function.compose, Predicate.and, etc.) due to the handy default methods they contain.
An interface with only one abstract method is called Functional Interface.
It is not mandatory to use #FunctionalInterface, but it’s best practice to use it with functional interfaces to avoid addition of extra methods accidentally. If the interface is annotated with #FunctionalInterface annotation and we try to have more than one abstract method, it throws compiler error.
package com.akhi;
#FunctionalInterface
public interface FucnctionalDemo {
void letsDoSomething();
//void letsGo(); //invalid because another abstract method does not allow
public String toString(); // valid because toString from Object
public boolean equals(Object o); //valid
public static int sum(int a,int b) // valid because method static
{
return a+b;
}
public default int sub(int a,int b) //valid because method default
{
return a-b;
}
}
Functional Interface:
Introduced in Java 8
Interface that contains a "single abstract" method.
Example 1:
interface CalcArea { // --functional interface
double calcArea(double rad);
}
Example 2:
interface CalcGeometry { // --functional interface
double calcArea(double rad);
default double calcPeri(double rad) {
return 0.0;
}
}
Example 3:
interface CalcGeometry { // -- not functional interface
double calcArea(double rad);
double calcPeri(double rad);
}
Java8 annotation -- #FunctionalInterface
Annotation check that interface contains only one abstract method. If not, raise error.
Even though #FunctionalInterface missing, it is still functional interface (if having single abstract method). The annotation helps avoid mistakes.
Functional interface may have additional static & default methods.
e.g. Iterable<>, Comparable<>, Comparator<>.
Applications of Functional Interface:
Method references
Lambda Expression
Constructor references
To learn functional interfaces, learn first default methods in interface, and after learning functional interface, it will be easy to you to understand method reference and lambda expression
You can use lambda in Java 8
public static void main(String[] args) {
tentimes(inputPrm - > System.out.println(inputPrm));
//tentimes(System.out::println); // You can also replace lambda with static method reference
}
public static void tentimes(Consumer myFunction) {
for (int i = 0; i < 10; i++)
myFunction.accept("hello");
}
For further info about Java Lambdas and FunctionalInterfaces
#FunctionalInterface is a new annotation are released with Java 8 and provide target types for lambda expressions and it used on compilation time checking of your code.
When you want to use it :
1- Your interface must not have more than one abstract methods, otherwise compilation error will be given.
1- Your interface Should be pure, which means functional interface is intended to be implemented by stateless classes, exmple of pure is Comparator interface because its not depend on the implementers state, in this case No compilation error will be given, but in many cases you will not be able to use lambda with this kind of interfaces
The java.util.function package contains various general purpose functional interfaces such as Predicate, Consumer, Function, and Supplier.
Also please note that you can use lambdas without this annotation.
Beside other answers, I think the main reason to "why using Functional Interface other than directly with lambda expressions" can be related to nature of Java language which is Object Oriented.
The main attributes of Lambda expressions are: 1. They can be passed around 2. and they can executed in future in specific time (several times). Now to support this feature in languages, some other languages deal simply with this matter.
For instance in Java Script, a function (Anonymous function, or Function literals) can be addressed as a object. So, you can create them simply and also they can be assigned to a variable and so forth. For example:
var myFunction = function (...) {
...;
}
alert(myFunction(...));
or via ES6, you can use an arrow function.
const myFunction = ... => ...
Up to now, Java language designers have not accepted to handle mentioned features via these manner (functional programming techniques). They believe that Java language is Object Oriented and therefore they should solve this problem via Object Oriented techniques. They don't want to miss simplicity and consistency of Java language.
Therefore, they use interfaces, as when an object of an interface with just one method (I mean functional interface) is need you can replace it with a lambda expression. Such as:
ActionListener listener = event -> ...;
Functional Interfaces: An interface is called a functional interface if it has a single abstract method irrespective of the number of default or static methods. Functional Interface are use for lamda expression. Runnable, Callable, Comparable, Comparator are few examples of Functional Interface.
KeyNotes:
Annotation #FunctionalInterface is used(Optional).
It should have only 1 abstract method(irrespective of number of default and static
methods).
Two abstract method gives compilation error(Provider #FunctionalInterface annotation is
used).
This thread talks more in detail about what benefit functional Interface gives over anonymous class and how to use them.
Related
Does Lambda completely demolish the usage the anonymous inner class from java 8?
I saw many examples how to convert anonymous inner classes to simple lambda expressions . i understand technical differences between both of them . But i just want to know when to when ? what is the business usecase scenario to use Anonymous Inner class after introduction of lambdas ? Does Lambda completely demolish the usage the anonymous inner class from java 8 ?
imagine this case interface Anon { void m1(); void m2(); } and a method that takes this interface void useAnon(Anon a); you will not be able to use lambda for this case. useAnon( new Anon(){ #Override void m1(){System.out.println("use m1");}; #Override void m2(){System.out.println("use m2");}; });
Lambdas can only be used in place of SAM (Single Abstract Method) classes. Sometimes these abstract classes are annotated with #FunctionalInterface to emphasise the fact that they can be replaced by a lambda expression. The answer to your question is No. Anonymous classes still have their usage, the lambda syntax is just there to simplify the creation of classes that only contain a single abstract method such as Function, Callable, etc,
How can Predicate be a Functional Interface if it has more than one abstract method? [duplicate]
Recently I started exploring Java 8 and I can't quite understand the concept of "functional interface" that is essential to Java's implementation of lambda expressions. There is a pretty comprehensive guide to lambda functions in Java, but I got stuck on the chapter that gives definition to the concept of functional interfaces. The definition reads: More precisely, a functional interface is defined as any interface that has exactly one abstract method. An then he proceeds to examples, one of which is Comparator interface: public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); } I was able to test that I can use a lambda function in place of Comparator argument and it works(i.e. Collections.sort(list, (a, b) -> a-b)). But in the Comparator interface both compare and equals methods are abstract, which means it has two abstract methods. So how can this be working, if the definition requires an interface to have exactly one abstract method? What am I missing here?
From the same page you linked to: The interface Comparator is functional because although it declares two abstract methods, one of these—equals— has a signature corresponding to a public method in Object. Interfaces always declare abstract methods corresponding to the public methods of Object, but they usually do so implicitly. Whether implicitly or explicitly declared, such methods are excluded from the count. I can't really say it better.
Another explanation is given in the #FunctionalInterface page: Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere. You can test which interface is a correct functional interface using #FunctionalInterface. E.g.: this works #FunctionalInterface public interface FunctionalInterf { void m(); boolean equals(Object o); } this generates an error: #FunctionalInterface public interface FunctionalInterf { void m(); boolean equals(); } Multiple non-overriding abstract methods found in interface FunctionalInterf
Q. But in the Comparator interface both compare() and equals() methods are abstract, which means it has two abstract methods. So how can this be working, if the definition requires an interface to have exactly one abstract method? What am I missing here? A. A functional interface may specify any public method defined by Object, such as equals( ), without affecting its “functional interface” status. The public Object methods are considered implicit members of a functional interface because they are automatically implemented by an instance of a functional interface.
An interface cannot extend Object class, because Interface has to have public and abstract methods. For every public method in the Object class, there is an implicit public and abstract method in an interface. This is the standard Java Language Specification which states like this, “If an interface has no direct super interfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.” That's how Object class' methods are declared in an interface. And according to JLS, this does not count as interface' abstract method. Hence, Comparator interface is a functional interface.
A functional interface has only one abstract method but it can have multiple default and static methods. Since default methods are not abstract you’re free to add default methods to your functional interface as many as you like. #FunctionalInterface public interface MyFuctionalInterface { public void perform(); default void perform1(){ //Method body } default void perform2(){ //Method body } } If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface’s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere. Comparator is a functional interface even though it declared two abstract methods. Because one of these abstract methods “equals()” which has signature equal to public method in Object class. e.g. Below interface is a valid functional interface. #FunctionalInterface public interface MyFuctionalInterface { public void perform(); #Override public String toString(); //Overridden from Object class #Override public boolean equals(Object obj); //Overridden from Object class }
Here is a "show me the code" approach to understanding the definition: we shall look into OpenJDK javac for how it checks validity of classes annotated with #FunctionalInterface. The most recent (as of July, 2022) implementation lies here: com/sun/tools/javac/code/Types.java#L735-L791: /** * Compute the function descriptor associated with a given functional interface */ public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError { // ... } Class Restriction if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0 || origin.isSealed()) { //t must be an interface throw failure("not.a.functional.intf", origin); } Pretty simple: the class must be an interface and must not be a sealed one. Member Restriction for (Symbol sym : membersCache.getSymbols(new DescriptorFilter(origin))) { /* ... */ } In this loop, javac goes through the members of the origin class, using a DescriptorFilter to retrieve: Method members (of course) && that are abstract but not default, && and do not overwrite methods from Object, && with their top level declaration not a default one. If there is only one method matching all the above conditions, then surely it is a valid functional interface, and any lambda will overwrite that very method. However, if there are multiple, javac tries to merge them: If those methods all share the same name, related by override equivalence: then we filter them into a abstracts collection: if (!abstracts.stream().filter(msym -> msym.owner.isSubClass(sym.enclClass(), Types.this)) .map(msym -> memberType(origin.type, msym)) .anyMatch(abstractMType -> isSubSignature(abstractMType, mtype))) { abstracts.append(sym); } Methods are filtered out if: their enclosing class is super class of that of another previously matched method, and the signature of that previously matched method is subsignature of that of this method. Otherwise, the functional interface is not valid. Having collected abstracts, javac then goes to mergeDescriptors, which uses mergeAbstracts, which I will just quote from its comments: /** * Merge multiple abstract methods. The preferred method is a method that is a subsignature * of all the other signatures and whose return type is more specific {#see MostSpecificReturnCheck}. * The resulting preferred method has a thrown clause that is the intersection of the merged * methods' clauses. */ public Optional<Symbol> mergeAbstracts(List<Symbol> ambiguousInOrder, Type site, boolean sigCheck) { // ... } Conclusion Functional interfaces must be interfaces :P , and must not be sealed or annotations. Methods are searched in the whole inheritance tree. Methods overlapping with those from Object are ignored. default methods are ignored, unless they are later overridden by sub-interfaces as non-default. Matching methods must all share the same name, related by override equivalence. Either there is only one method matching the above conditions, or matching methods can get "merged" by their class hierarchy, subsignature relations, return types and thrown clauses.
The Java docs say: Note that it is always safe not to override Object.equals(Object). However, overriding this method may, in some cases, improve performance by allowing programs to determine that two distinct comparators impose the same order. Maybe Comparator is special? Maybe, even though it's an interface, there is somehow a default implementation of equals() that calls compare()? Algorithmically, it's trivial. I thought all methods that were declared in interfaces were abstract (i. e. no default implementation). But maybe I'm missing something.
Definition: If an interface contains only one abstract method, then such type of interface is called functional interface. Usage: Once we write Lambda expression "->" to invoke its functionality , then in this context we require Functional Interface. We can use the Functional Interface reference to refer Lambda expression. Inside functional interface we can have one abstract method and n number of default/static methods. Functional interface with respect to inheritance: If an interface extends Functional interface and the child interface does not contain any abstract method , then the child interface is also considered to be Functional Interface. Functional interface is not new to java, its already used in following interface API's: Runnable : contains run() method only. Callable : contains call() method only. Comparable : contains compareTo() method only.
Before Java 8, an interface could only declare one or more methods also known as Abstract Method (method with no implementation, just the signature). Starting with Java 8 an interface can also have implementation of one or more methods (knows as Interface Default Method) and static methods along with abstract methods. Interface Default Methods are marked default keyword. So the question is, what is Functional Interface? An interface with Single Abstract Method (SAM) is called Functional Interface. Which means - An interface with Single Abstract Method is a Functional Interface An interface with Single Abstract Method and zero or more default methods and zero or more static method is also a valid Functional Interface. More detail with example code https://readtorakesh.com/functional-interface-java8/
My confusion with Java Lambda expression
I know that Java's Lambda expression can replace a parameter whose type is an Interface (only contains one method), but why I can execute code like this: String[] myArray = new String[3]; Arrays.sort(myArray, (a, b) -> {return b.compareTo(a);}); In this case, the lambda expression (a, b) -> {return b.compareTo(a);} replaces an object of Comparator interface, but Comparator interface has more than one method, why?
You can do this because Comparator only declares one method for which there is no default implementation. (You may notice that it redeclares equals without an implementation, but this is only to document the effect of overriding it in a Comparator. A default implementation is inherited from Object, as discussed here.)
From the JavaDocs for java.util.Comparator: Functional Interface: This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. java.util.Comparator is annotated with #FunctionalInterface which is: used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method.
The comparator interface contains only 1 method: compare(...) Because of this it is a functional interface which can be used with lambdas.
Are there dangers in making an existing Java interface functional?
As a rule, in the context of a large project, is it considered safe to take make an existing, ubiquitously used interface into a functional interface? E.g., given an existing interface and class: public interface Interface { public double calculateSomething(double x); public void doSomething(); } which is implemented by class InterfaceImplementer implements Interface { public double calculateSomething(double x) { return 2 * x; } public void doSomething() { // insert specific behavior here } } can I safely change the interface by defining all but one method as default: public interface Interface { public double calculateSomething(double x); default void doSomething() { // insert some default behavior here } } So that I can go from defining an object as Interface object = new InterfaceImplementer() { #Override public double calculateSomething(double x) { return 2 * x; } }; to Interface object = (x) -> 2 * x; while still being able to define objects in the old, tedious way. From what I can tell, this runs no risk of upsetting any existing code, and I've made such a change to a large project and had no runtime or compile errors. But I want some confirmation whether this matches up with common knowledge and best practices.
Any interface that only has a single non-default method (only one method needs to be implemented in a class) is by definition a functional interface. This is a good rule! However, a #FunctionalInterface annotation has the advantage of enforcing the "only one method in the interface for a functional interface"-rule. So if you added it to your original two-method interface, you would have gotten a compiler error. Therefore by explicitly adding #FunctionalInterface you declare your intent and make your code more clear to future maintainers.
On java code level, I can think of one problem: since this interface already had contained 2 methods at some point in the past, you may want to add another method to it later on. You won't be able to add another method to a functional interface, since it has to remain a functional interface so you can use it as a functional interface. You will have to create an interface that inherits from this one. Which leads me to the main point. It may have been logical to have those 2 methods in one interface before, but is it really logical now? Refactor the code, separate the interfaces; either make one extend another or use an interface that inherits from both, your call. If the interface is to be used as a functional one, make it functional. It will be clean. It will be understandable. You will be able to add methods to one of those interfaces in the future without further refactoring.
The Java API states: However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. Therefore there is no risk to add that annotation.
Well, it's not the #Functional that might break anything, but adding a default implementation may lead to compilation errors for abstract classes that implement or interfaces that extend multiple interfaces declaring methods with override-equivalent signatures: The following compiles fine: interface I { void a(); } interface J { void a(); } interface K extends I, J {} while this doesn't: interface I { default void a() {} } interface J { void a(); } interface K extends I, J {} The default method a() inherited from I conflicts with another method inherited from J So if you do this in a library, code using this may fail to compile after the change.
Functional interfaces in Java 8
I'm having a hard time sorting out why lambda expressions are assignable to some functional interfaces, but not others. An example, using some functional interfaces from the Metrics library: Gauge<Double> foo = () -> { return null; }; RatioGauge bar = () -> { return null; }; The second statement has a compile error (in Eclipse): The target type of this expression must be a functional interface As far as I can tell, RatioGauge is a functional interface. Am I missing something?
An abstract class (even if it only has one abstract method) is not a functional interface. Only an interface can be one. From JLS 9.8: A functional interface is an interface that has just one abstract method (aside from the methods of Object)... (emphasis added) The original idea was to let abstact classes be expressed as a lambda; they were called "SAM types," which stood for "single abstract method." That turned out to be a difficult problem to solve efficiently. This thread talks a bit about why; basically, the base class's constructor made it difficult.
A function interface can have only ONE abstract method (besides the methods from Object class). Source code for Gauge.java= http://grepcode.com/file/repo1.maven.org/maven2/com.codahale.metrics/metrics-core/3.0.0/com/codahale/metrics/Gauge.java#Gauge Source code for RatioGauge.java= http://grepcode.com/file/repo1.maven.org/maven2/com.codahale.metrics/metrics-core/3.0.0/com/codahale/metrics/RatioGauge.java Notice that Gauge.java only has one abstract method while RatioGauge has many methods.