Java Closures with lambda expressions.

suggest change

A lambda captures variables from an enclosing scope. The rules for local variables are the same as for anonymous classes.

Local variables from an enclosing scope that are used within a lambda have to be final or effectively final. Since Java 8, the earliest version that supports lambdas, they don’t need to be declared final, but they must not be assigned after they are captured. For example:

int n = 0; // effectively final; it need not be declared final
Runnable r = () -> { // Using lambda
    int i = n;
    // do something
};

This is legal as long as the value of the n variable is not changed. If you try to change the variable, inside or outside the lambda, you will get the following compilation error:

“local variables referenced from a lambda expression must be final or effectively final”.

For example:

int n = 0;
Runnable r = () -> { // Using lambda
    int i = n;
    // do something
};
n++; // Will generate an error.

To keep using the original variable after the lambda is created, copy its current value and capture the copy. The lambda does not see later assignments to the original. For example:

int n = 0;
final int k = n; // the copy is final; declaring it final is optional when it is not reassigned
Runnable r = () -> { // Using lambda
    int i = k;
    // do something
};
n++;      // Now will not generate an error
r.run();  // Will run with i = 0 because k was 0 when the lambda was created

Naturally, the body of the lambda does not see the changes to the original variable.

A lambda cannot observe later assignments to a local variable. It can observe changes to fields of an enclosing instance, and to the objects a captured reference points at. A mutable local has to be held in an object or a field. For example:

// Does not compile ...
public IntUnaryOperator createAccumulator() {
    int value = 0;
    IntUnaryOperator accumulate = (x) -> { value += x; return value; };
    return accumulate;
}

The above example will not compile for reasons discussed previously. We can work around the compilation error as follows:

// Compiles, but is incorrect ...
public class AccumulatorGenerator {
    private int value = 0;

    public IntUnaryOperator createAccumulator() {
        IntUnaryOperator accumulate = (x) -> { value += x; return value; };
        return accumulate;
    }
}

IntUnaryOperator does not forbid mutable state. This lambda is legal, and each call sees the updated field. Stream methods and other APIs that require a stateless function can return wrong results if they receive this operator. When the mutable behavior is the point of the type, a named class makes that obvious. For example:

// Correct ...
public class Accumulator {
   private int value = 0;

   public int accumulate(int x) {
      value += x;
      return value;
   }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents