0

I am referencing to a book by Cay S. Horstmann and came across lambda expressions.

A lambda expression can capture the value of a variable in the enclosing scope, but can only reference variables whose value doesn’t change.

With this in my mind I got confused with the use of this reference inside a lambda expression. What confused me is when we use this reference inside a lambda expression, in a non-static method, can we mutate the object that this refers?

  • 1
    Thats basically the https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value discussion. Value of the variable is the reference/pointer itself, not the referenced object. So you can't change what object the variable references, but you can change the object. – k5_ Mar 28 '20 at 22:16
  • @k5_ Oh! now I got it thanks a lot, it's just the variable e can't change we can mutate what the variable holds. – Neminda Prabhashwara Mar 28 '20 at 22:24
  • @NemindaPrabhashwara you can change the value. See if my example is what you were talking about. – WJS Mar 28 '20 at 22:30
  • @WJS your answer helped through it. – Neminda Prabhashwara Mar 28 '20 at 22:35

1 Answers1

2

If this is what you are talking about you can mutate them all you want since a is not a local variable. This example uses Function.

public class MutatingTest {
    int a = 0;
    public static void main(String[] args) {
        new FinalTest().start();
    }

    public void start() {
        Function<Integer,Integer> app = b->b + this.a++;

        int v = app.apply(10); 
        System.out.println(v);

        v = app.apply(10); 
        System.out.println(v);

        v = app.apply(10); 
        System.out.println(v);

        v = app.apply(10); 
        System.out.println(v);
    }
}

prints

10
11
12
13
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
WJS
  • 22,083
  • 3
  • 14
  • 32