Java 8 type inference error, assigning lambda expression to variable of object type
Why does the java compiler complain about the first statement? This is because the expression () – > "" does not have an explicit type. I mean that it may be a vendor < string > or a custom function interface type?
Object emptyStringBuilder = () -> ""; // causes compiler error Object emptyStringBuilder = (supplier<String>)() -> "";
Can you elaborate on the exact reason?
Solution
The type inference of a lambda expression comes from the target type, which means that when you write something like this:
() -> "";
This is indeed a vendor (for you, not the compiler), but if I have a type declaration as follows:
static interface Producer<T> {
T produce();
}
This means that your lambda can be a producer or supplier Therefore, the assignment must be @ functionalinterface (or cast) so that type inference can be made
In JLS, these are defined as multiple expressions (they depend on their environment – such as generics, method references, ternary operators)
