代码之家  ›  专栏  ›  技术社区  ›  Neminda Prabhashwara

我们能在lambda表达式中改变这个引用吗?

  •  0
  • Neminda Prabhashwara  · 技术社区  · 6 年前

    我在参考凯伊·S·霍斯特曼的一本书时,偶然发现了lambda的表达式。

    lambda表达式可以捕获封闭作用域中变量的值,但只能引用其值不变的变量。

    在我的脑海里,我对 this 这 lambda表达式中的引用,在非- static 方法,我们能改变 指?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Basil Bourque    6 年前

    如果这就是你所说的,你可以把它们全部变异 a 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);
        }
    }
    

    10
    11
    12
    13