Functional Interface Definition
Contains only one abstract method.
Can have standard and/or static methods.
Abstract method does not specify implementation.
MyValue interface {
double getValue();
}
Reminder: In functional interfaces, the abstract modifier is not explicitly needed, as Java assumes that any method that has no implementation in an interface is automatically abstract.
Assigning a Lambda to a Functional Interface
MyValue myVal = () -> 98.6;
The return type and parameters of the lambda must be compatible with the abstract method.
Abstract method call:
System.out.println("A constant value: " myVal.getValue());
Result: 98.6.
Functional Interfaces with Parameters
MyParamValue interface {
double getValue(double v);
}
Lambda with calculation of the reciprocal:
MyParamValue myPval = (n) -> 1.0 / n;
System.out.println("Reciprocal of 4 is " myPval.getValue(4.0));
Type Inference
Parameter type inferred by context:
(n) -> 1.0/n; // Type inferred as double
Explicitly declared type (optional):
(double n) -> 1.0 / n;
Compatibility Rules
(int x, int y) -> x y;
Conclusion
Functional interfaces enable the use of lambdas.
Lambda expressions provide a concise implementation for the abstract method.
Target type contexts and type compatibility are crucial to its use.
The above is the detailed content of Functional interfaces. For more information, please follow other related articles on the PHP Chinese website!