Junior — Middle
How is the return type of Lambda expressions in Java determined?
sobes.tech AI
Answer from AI
The return type of lambda expressions in Java is determined by the context in which the lambda is used, specifically the functional interface to which it is assigned.
Each functional interface has one abstract method with a defined signature, including the return type. The compiler looks at this method and infers the lambda's return type from its signature.
For example:
interface Calculator {
int calculate(int a, int b);
}
Calculator sum = (a, b) -> a + b; // return type is int, as in the calculate method
Here, the lambda (a, b) -> a + b returns int because the calculate method returns int.
If the lambda is used without the context of a functional interface, the compiler cannot determine the return type.