Home > Java > javaTutorial > Lambda expressions and capturing variables

Lambda expressions and capturing variables

Mary-Kate Olsen
Release: 2025-01-12 06:29:45
Original
657 people have browsed it

Expressões lambda e a captura de variáveis

Access to Variables in the Contained Scope

  • A lambda expression can access:
  • Instance variables of the containing class.
  • Static variables defined in the external class.
  • The this parameter, which references the calling instance of the external class.

Access to Local Variables

  • When using external scope local variables:
  • The local variable must be effectively final.
  • Effectively final: A variable whose value does not change after being assigned.
  • Does not need to be explicitly declared as final.
  • Modifying the local variable (inside or outside the lambda) invalidates its capture.

Modification Restriction
Cannot modify:

  • Local variables captured within the lambda expression.
  • Modifying these variables removes their effectively final status.

Modification of Instance Variables
A lambda expression can:

  • Use and modify instance variables of the calling class.
  • There is no restriction on "final" status for instance variables.

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;
    }
}

Copy after login

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template