I am doing some experiment with lambda expression and saw some behavior which I can't understand.
Consumer consumer = (o1) -> {};
Object obj1 = consumer; // this two line working fine
Above 2 lines of code does not complain anything as expected when I assign consumer
to obj1
.
However when I tried to assign directly the lambda to object it started giving me a compilation error.
Object obj2 = (o1) -> {}; // this line gives compilation error
The above line of code gives me an error :
The target type of this expression must be a functional interface.
My question is why we can't directly assign a lambda to a reference variable of type Object
?
Edited: I have edited my question as there is a similar question already mentioned but my question main goal was to ensure why Object o1 = "Hello"
will work but not the lambda.
If you assign a lambda expression to a variable of type Object
, the compiler has no idea which functional interface this lambda expression should implement.
For example, the lambda expression o -> o.toString ()
can be assigned to either a Consumer
or a Function
:
Consumer<String> cons = o -> o.toString ();
Function<String,String> cons2 = o -> o.toString ();
Therefore you have to either assign the lambda expression to a variable of a functional interface type or to cast the lambda expression to some functional interface type before assigning it to the Object
variable.