Variable Capture

Description

A lambda expression can access final local variables or local-non-final-initialized-only-once variables.

Example

The following code shows that we can access and use the final local variables.


import java.util.function.Function;
/*w  ww . j a v a 2s.  c o m*/
public class Main {
  public static void main(String[] argv) {
    final String x = "Hello"; 
    Function<String,String> func1 = y -> {return y + " "+ x ;};
    System.out.println(func1.apply("java2s.com"));

  }
}

The code above generates the following result.

Example 2

The following code has a variable x which is not final but only initialized once. We can still use it in the lambda expression.


import java.util.function.Function;
//from  w  ww. j av  a 2s .  c  o m
public class Main {
  public static void main(String[] argv) {
    String x = "Hello"; 
    
    Function<String,String> func1 = y -> {return y + " "+ x ;};
    System.out.println(func1.apply("java2s.com"));
    
  }
}

The code above generates the following result.

Example 3

The following code shows that we cannot change the value defined outside lambda expression.


import java.util.function.Function;
//from w w w.  j a  va  2s. co m
public class Main {
  public static void main(String[] argv) {
    String x = "Hello"; 
    
    Function<String,String> func1 = y -> {/*x="a";*/ return y + " "+ x ;};
    System.out.println(func1.apply("java2s.com"));
    
  }
}

The code above generates the following result.

Example 4

We can change the non-local variable in lambda expression.


import java.util.function.Function;
//from   w w w. j av  a 2  s . co  m
public class Main {
  static String x = "Hello"; 
  public static void main(String[] argv) {

    
    Function<String,String> func1 = y -> {x="a"; return y + " "+ x ;};
    System.out.println(func1.apply("java2s.com"));
    
  }
}

The code above generates the following result.





















Home »
  Java Lambda »
    Java Lambda Tutorial »




Java Lambda Tutorial