How do lambda expressions implement and interact with functional interfaces in programming languages?
sobes.tech AI
Answer from AI
In Java, lambda expressions implement functional interfaces — interfaces with a single abstract method. A lambda expression is essentially an implementation of that single method.
When the compiler encounters a lambda, it associates it with a functional interface, determining the method's signature. At runtime, the JVM creates an instance of this interface, where the method is implemented through the lambda body.
Example:
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
Calculator sum = (a, b) -> a + b;
int result = sum.calculate(5, 3); // result = 8
Here, the lambda (a, b) -> a + b implements the calculate method. This allows writing concise and expressive code, passing behavior as a parameter.
Thus, lambda expressions and functional interfaces are closely related: a lambda is a short implementation of a method of a functional interface, simplifying functional programming in Java.