Access to Variables in the Contained Scope
Access to Local Variables
Modification Restriction
Cannot modify:
Modification of Instance Variables
A lambda expression can:
Example: Capturing Local Variable from External Scope
Code:
interface MyFunc { int func(int n); } class VarCapture { public static void main(String args[]) { // Variável local que pode ser capturada int num = 10; MyFunc myLambda = (n) -> { // Uso correto da variável num int v = num + n; // A instrução abaixo é inválida porque tenta modificar num // num++; return v; }; // Usando a expressão lambda System.out.println(myLambda.func(8)); // Exibe: 18 // Modificar num aqui também causaria erro // num = 9; } }
Explanation:
Num Capture:
num is effectively final because it is not changed after the initial assignment.
Lambda can access num, but cannot modify it.
Execution:
myLambda.func(8) returns 18 because:
num (10) is added to the parameter n (8), producing 18.
Error due to Modification:
Uncommenting num or num = 9 would invalidate the capture, causing a compilation error.
Note:
Important: Instance or static variables can be used and modified without restrictions within lambda expressions.
Restrictions apply only to external scope local variables.
The above is the detailed content of Lambda expressions and capturing variables. For more information, please follow other related articles on the PHP Chinese website!