Java Lambda Expression and Variable Capture

Introduction

Variables from the enclosing scope of a lambda expression are accessible within the lambda expression.

A lambda expression can obtain or set the value of an instance or static variable and call a method defined by its enclosing class.

A lambda expression may only use local variables that are effectively final.

An effectively final variable is one whose value does not change after it is first assigned.

A local variable of the enclosing scope cannot be modified by the lambda expression.

The following program illustrates the difference between effectively final and mutable local variables:

interface MyFunc {
  int func(int n);
}

public class Main {
  public static void main(String args[]) {
    // A local variable that can be captured.
    int num = 10;
    MyFunc myLambda = (n) -> {/*from   w  w  w.  java 2  s  .com*/
      // This is OK. It does not modify num.
      int v = num + n;

      // illegal because it attempts
      // to modify the value of num.
      // num++;
      return v;
    };

    // num = 9;
  }
}

A lambda expression can use and modify an instance variable from its invoking class.

It can't use a local variable of its enclosing scope unless that variable is effectively final.




PreviousNext

Related