Content deleted Content added
GreenC bot (talk | contribs) Move 1 url. Wayback Medic 2.5 |
A variable in Java needn't be declared final, as long as its value isn't changed in practice. |
||
Line 12:
Some efficiency-minded compilers employ a hybrid approach in which the activation records for a function are allocated from the stack if the compiler is able to deduce, through [[static program analysis]], that the function creates no upwards funargs. Otherwise, the activation records are allocated from the heap.
Another solution is to simply copy the value of the variables into the closure at the time the closure is created. This will cause a different behavior in the case of mutable variables, because the state will no longer be shared between closures. But if it is known that the variables are constant, then this approach will be equivalent. The [[ML (programming language)|ML]] languages take this approach, since variables in those languages are bound to values—i.e. variables cannot be changed. [[Java_(programming_language)|Java]] also takes this approach with respect to anonymous classes (and lambdas since Java 8), in that it only allows one to refer to variables in the enclosing scope that are effectively <code>final</code> (i.e. constant).
Some languages allow the programmer to explicitly choose between the two behaviors. [[PHP]] 5.3's anonymous functions require one to specify which variables to include in the closure using the <code>use ()</code> clause; if the variable is listed by reference, it includes a reference to the original variable; otherwise, it passes the value. In Apple's [[Blocks (C language extension)|Blocks]] anonymous functions, captured local variables are by default captured by value; if one wants to share the state between closures or between the closure and the outside scope, the variable must be declared with the <code>__block</code> modifier, in which case that variable is allocated on the heap.
|