Captured value of a lambda semantics

andrei.eremeev andrei.eremeev at oracle.com
Thu Apr 23 14:14:53 UTC 2015


Hi,

REPL just wraps Java code into classes and methods.
So, in this case IntUnaryOperator addTwo = x -> x + a; is wrapped into 
some method. So, 'a' is an external variable, not local.
When 'a' is declared, it is wrapped into a class with field 'int a'. 
Thus, the lambda expression refers to this field. Changing of variable 
'a' is changing of field 'a'.
Thus, the result of the 18 line is 5.

Thank you for using REPL in studying. This is one of the aims why this 
tool is being developed.

Andrei

On 04/23/2015 04:56 PM, Remi Forax wrote:
> Hi guys,
> I've shown to some of my students how to play with the REPL
> (and how to compile it in Eclipse but that's another war story ...)
>
> One of my student send me this snippet:
>    9 : import java.util.function.*;
>   10 : IntUnaryOperator addOne = x -> x + 1;
>   11 : addOne.applyAsInt(2)
>   12 : addOne.applyAsInt(2
>        )
>   13 : addOne.applyAsInt(3)
>   14 : IntUnaryOperator addTwo = x -> x + a;
>   15 : int a = 2;
>   16 : addTwo.applyAsInt(2)
>   17 : a = 3
>   18 : addTwo.applyAsInt(2)
>
> as you may guess, the last expression result is 5 which is not the 
> standard Java semantics,
> is there a reason for that, or is this a side effect of declaring 'a' 
> after the lambda ?
>
> cheers,
> Rémi
>



More information about the kulla-dev mailing list