How does java lambdas external references work?

Viewed 91

I'm wondering how does lambdas external references work. Let me explain:

Suppose i have this supplier implementation and this model class :

public class TestSupplierImpl implements Supplier<Boolean> {

    public Predicate<Integer> predicate;
    public TestSupplierModel model;

    public TestSupplierImpl() {
        this.predicate = i -> model.something.equals(i);
    }

    @Override
    public Boolean get() {
        return predicate.test(3);
    }
}


    class TestSupplierModel {
        public Integer something;

        public TestSupplierModel(Integer something) {
            this.something = something;
        }
    }

Then i execute the following code:

    TestSupplierImpl test = new TestSupplierImpl(); // line 1
    test.model = new TestSupplierModel(3); // line 2
    Boolean resultado = test.get(); // line 3

Line 1: creating a new instance of TestSupplierImpl. This new instance's predicate has a null reference of model. This makes sense because at the moment of creation of the predicate, model reference is null. Line 2: assign to variable model a new instance of TestSupplierModel. Line 3: test.predicate now has model reference with the new assigned value. Why is this ?

I don't understand why ,when I changed model reference, the predicate updates its model reference to the new one. How is that ?

Thanks in advance !

1 Answers

Does it make sense if you rewrote your TestSupplierImpl() constructor as follows?


    public Predicate<Integer> predicate;
    public TestSupplierModel model;

    public TestSupplierImpl() {
        // same effect as this.predicate = i -> model.something.equals(i);
        this.predicate = new Predicate<Integer>() {
            public boolean test(Integer i) {
                return model.something.equals(i);
            }
        };
        
    }

    @Override
    public Boolean get() {
        return predicate.test(3);
    }

So here is the order of things.

        // the constructor is run and the test method defined BUT NOT executed.
        TestSupplierImpl test = new TestSupplierImpl(); // line 1
       
        // Now you define model
        test.model = new TestSupplierModel(3); // line 2
        
        // Then you execute the predictate via get()
        Boolean resultado = test.get(); // line 3


model and something aren't required until you issue the get() method. By that time they are already defined.

Related