A lambda expression is an instance of a functional interface. But a lambda expression itself does not contain the information about which functional interface it is implementing; that information is deduced from the context in which it is used. For example, the expression
x -> 2 * x
can be an instance of the functional interface
interface IntOperation { int operate(int i); }
so it is legal to write
IntOperation iop = x -> x * 2;
The type expected for the expression on the right-hand side of the assignment here is IntOperation
. This is called the target type for the lambda expression. Clearly a lambda expression can be type-compatible with different functional interfaces, so it follows that the same lambda expression can have different target types in different contexts. For example, given an interface
interface DoubleOperation { double operate(double i); }
it would also be legal to write
DoubleOperation dop = x -> x * 2;
The target type for a lambda expression must be a functional interface and, to be compatible with the target type, the lambda expression must have the same parameter types as the interface’s function type, its return type must be compatible with the function type, and it can throw only exceptions allowed by the function type.
An interface having only a single
abstract method: see this page
Roughly, the type of its single abstract method; for a more
precise explanation see the syntax notes to this page
I don’t think that the question in the heading is really answered. For example,
x -> 2 * x
is a lambda expression but it has no type in isolation. I think that it’s worth noting that it doesn’t make sense in Java 8 to talk about the type of a lambda expression, any more than it would make sense to talk about the type of an expression with a “diamond” such as new HashSet<>().
I don’t agree with this. Although it’s true that a lambda expression in isolation may have many possible types (note: not “no type”), when it is placed in context the compiler must be able to infer a precise type for it, or the code won’t compile. Maybe the question is really “What is the type of a lambda expression when it is part of a well-typed statement or expression?”. As a title that’s rather unwieldy, but it’s the question that I’ve tried to answer.
[…] blog of Maurice Naftalin is a great place to learn lambda expression […]