Why is the java compiler complaining about the first statement, it's because the expression () -> ""
doesn't have a definite type, i mean it could be a Supplier <String>
or a custom functional interface type, etc ... ?
Object emptyStringBuilder = () -> ""; // causes compiler error
Object emptyStringBuilder = (Supplier<String>)() -> "";
Could you elaborate on the exact causes please ?
Lambda expression implements @FunctionalInterface
- an interface with just a single public non-static and non-default method. In the first case compiler gets type from the left side - Object
, because it cannot infer a type of your lambda expression. Compiler wont pick any interface for you. And Object
does not implement functional interface, so compiler complains about this situation.
In second case you use functional interface Supplier<T>
and you assign it to an Object
which is correct in terms of compilation - compiler is satisfy because you cast down your specific type (Supplier<T>
in that case) to a most general Object
(every class inherits from Object
class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With