Home > Java > javaTutorial > Functional interfaces

Functional interfaces

Patricia Arquette
Release: 2025-01-07 08:10:40
Original
418 people have browsed it

Interfaces funcionais

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));

  • Result: 0.25.

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

  • The type and number of parameters in the lambda expression must match the abstract method.

(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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template