Captured value of a lambda semantics
Remi Forax
forax at univ-mlv.fr
Thu Apr 23 14:26:13 UTC 2015
Ok, I understand why the result is 5.
But I think this should be fixed, it's not a good idea to have two
different semantics,
the REPL semantics and the Java semantics.
ipython has this exact sample problem and as a teacher, it's hard to
explain why something works in a way in the REPL and in another way in
the compiler.
regards,
Rémi
On 04/23/2015 04:14 PM, andrei.eremeev wrote:
> 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