0

as read

Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

what I understand that lambda is replacement of inner classes with single method to eliminates the bulkiness of the code

public class Main {

    interface Foo {
        int x = 20;
        void bar();
    }

    public static void main(String[] args) {
        Main app = new Main();
        app.start();
    }

    int x = 10;

    public void start()
    {
        Main test = new Main();
        test.test(new Foo()
        {
            @Override
            public void bar() {
                System.out.println("Inner Class X= " + this.x);
            }
        });

        test.test(() -> System.out.println("Lambda X= " + this.x));
    }

    public void test(Foo foo) {
        foo.bar();
    }

}

the output I get is

Inner Class X = 20
Lambda X = 10

what I expect is

Inner Class X = 20
Lambda X = 20
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
  • 1
    `this` refers to different things in a lambda Vs an anonymous class. Why? Because that's how the two are defined in the language spec. – Andy Turner Jan 24 '18 at 07:32
  • both times you called this, it was in the scope of a different class. – Stultuske Jan 24 '18 at 07:34
  • 1
    Aside from anything else, `x` is static on `Foo`, so don't try to refer to it through an instance. – Andy Turner Jan 24 '18 at 07:36
  • Relevant language spec [quote](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.8.3): "The value denoted by this in a lambda body is the same as the value denoted by this in the surrounding context." – Andy Turner Jan 24 '18 at 07:40

1 Answers1

-1

Consider that a lambda is not an object.

We your first implementation, you make an object of the inner class by doing new Foo(). So in this implementation this refers to this object.

In the lambda implementation, there is not such an object an this refers to the enclosing class.

Prim
  • 2,880
  • 2
  • 15
  • 29