Where scope variables are stored for lambda expressions

As I know for inner and anonymous classes, variables of the outer scope are stored in the generated bytecode (for example, OuterClass $ 1.class). I would like to know where the variables of the following example are stored:

public Function<Integer, Integer> curring(Integer elem) {
    return x -> x * elem;
}

Arrays.asList(1, 2, 3, 4, 5).stream().map(curring(2)).map(curring(5)).forEach(System.out::println);

Lambda translates to methods, not classes. Does this mean that two separate methods will be created for this 2 calls?

+4
source share
2 answers

This expression x -> x * elem;will be rejected to a static method, which looks like this:

  private static Integer lambda$curring$0(int x, int y){
      return x*y;
  }

Since you are a capturingvariable eleminside lambda, lambda is called stateful lambda.

, map java.util.Function - , :

 final class Test2$$Lambda$1 implements java.util.function.Function {
      private final Integer arg$1;

      private Test2$$Lambda$1(Integer arg$1){
          this.arg$1 = arg$1;
      }

      // static factory method
      private static java.util.function.Function get$Lambda(Integer i){
            return new Test2$$Lambda$1(i); // instance of self
      }

       public Integer apply(Integer x) {
          return YourClass.lambda$curring$0(this.arg$1, x);    
       }
 }

Function.apply ( ) Test2$$Lambda$1, factory get$Lambda. "" elem.

- , , .

Stream , 10 - map.

, - . ( ) , .

+7

, curring(..), . , 2 .

, , . , elem.

, elem , 2:

public Function<Integer, Integer> curring() {
    return x -> x * 2;
}

. - . , .

, JVM, JVM HotSpot.

: , ?

+3

Source: https://habr.com/ru/post/1676540/


All Articles