Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 479
marsouf Avatar asked Aug 03 '17 15:08

marsouf


1 Answers

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).

like image 76
Szymon Stepniak Avatar answered Sep 30 '22 20:09

Szymon Stepniak