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.