-1

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.

Amit Bera
  • 7,075
  • 1
  • 19
  • 42
  • 1
    @VinayPrajapati Thanks!!! However, I was wondering how Object o1 = "Hello" works but lambda expression can work in the same way but now it is clear. – Amit Bera Apr 12 '18 at 12:26
  • I would recommend deletion of this Question @Amit! – Vinay Prajapati Apr 12 '18 at 12:30
  • The duplicate question mentioned here not that much clear to me like if Object o1 = "Hello"; works in java why not the lambda. – Amit Bera Apr 12 '18 at 12:32
  • 1
    I assume you are using [`java.util.function.Consumer`](https://docs.oracle.com/javase/9/docs/api/java/util/function/Consumer.html)? If so, please be aware that you are using a [raw type, which you should always avoid](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). – Turing85 Apr 12 '18 at 12:39
  • @Turing85 You are right and thanks for your suggestion. That was just for testing code that's why I had not put generic type. – Amit Bera Apr 12 '18 at 12:42

2 Answers2

7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Because Java compiler uses a property type to recognize fields of an anonymous class the lambda denotes. According to Oracle tutorials a lambda is just a convenient approach to denote anonymous classes with a lone method and create the objects of the classes. The Object class has more methods, and it is a class. Lambdas are used along with interfaces.