What does capturing a variable mean? #javalanguage #javacoding #javatips #javacodinginterview

preview_player
Показать описание
Cracking the #Java #Coding #Interview - Question 213: What does capturing a variable mean?
Рекомендации по теме
Комментарии
Автор

I remember that in earlier versions of Java one had to explicitly declare the captured variable as final. If a method parameter was to be captured, one had to add the "final" keyword to the parameter or alternatively create a final copy of the parameter. That was quite ugly. I am happy that this was eventually relaxed into the requirement that the captured variable only needs to be effectively final.

michaelschneider
Автор

If you want an ad hoc mutable scope for a lambda, try this:

var x = new Object() { int a; float b; };

var will give x the actual type (not simply Object), so you can freely read and write its fields.

In older versions of Java, you can declare a named local class, but this saves a bit of typing.

nisonatic
Автор

In the case of fields, the thing that's captured are not the individual fields but the implicit `this` reference of the enclosing instance (you can see this in the debugger).
What the lambda `() -> value` in the example really translates to is `() -> Box.this.value` and it's `Box.this` that gets captured by the lambda, not `Box.this.value` itself.
That's why you're allowed to assign fields of a captured enclosing instance, just as you're allowed to assign fields of any captured object.

jay_sensz
Автор

It might be interesting to learn more about the race conditions that could occur. Because everybody knows that people continuously work around the final limit by using arrays (or AtomicXxxx). So shouldn't that be forbidden as well? Or should we just trust devs to know when it's safe to use non-final variables?

quintesse
welcome to shbcf.ru