Java 8 type input error, assigning a lambda expression to a variable of type Object

Why () -> ""does the java compiler complain about the first statement because the expression does not have a specific type, I mean that it can be Supplier <String>either a user-type functional interface, etc. ??

Object emptyStringBuilder = () -> ""; // causes compiler error

Object emptyStringBuilder = (Supplier<String>)() -> "";

Could you elaborate on specific reasons?

+6
source share
2 answers

Type inference for a lambda expression comes from the target type, that is, when you write something like this, for example:

 () -> "";

This is valid Supplier(for you, not the compiler), but what if I have a type declared as follows:

static interface Producer<T> {
    T produce();
}

, Producer Supplier. , @FunctionalInterface ( ), .

JLS ( , - , , , )

+1

Lambda expression @FunctionalInterface - . - Object, -. - . Object , .

Supplier<T> Object, - , (Supplier<T> ) Object ( Object).

+3

All Articles