Why can method reference use non-final variables?

后端 未结 4 1757
后悔当初
后悔当初 2020-12-01 09:19

I had some confusion about inner classes and lambda expression, and I tried to ask a question about that, but then another doubt arose, and It\'s probable better posting ano

4条回答
  •  猫巷女王i
    2020-12-01 09:49

    No. In your first example you define the implementation of F inline and try to access the instance variable one.

    In the second example you basically define your lambda expression to be the call of bar() on the object one.

    Now this might be a bit confusing. The benefit of this notation is that you can define a method (most of the time it is a static method or in a static context) once and then reference the same method from various lambda expressions:

    msg -> System.out::println(msg);
    

提交回复
热议问题