简体   繁体   中英

Java Lambda vs Method Reference - One does not receive the local vars of the caller

Trying to refactor from a lambda to a method reference I realized that there seems to be a difference in method references not getting the local variables of the caller (the lexical scope?). When using a lambda as its inline code there isn't problem at all.

public class MethodRef {

  public static void main(String[] args) {
    String appender = "I am appended";

    //possible
    appender("Hello! ", former ->  {
      StringBuilder builder = new StringBuilder(former);
      builder.append(appender);
      System.out.println(builder.toString());
    });

    //not possible
    appender("Hello! ", this::theRef);
  }

  //Delegater
  public static void appender(String former, Consumer<String> consumer){
      consumer.accept(former);
  }

  //Method Ref
  public void theRef(String former){
    StringBuilder builder = new StringBuilder(former);
    builder.append(appender);
    System.out.println(builder.toString());
  }
}

I understand the fact that the param list of the method does not yield any "appender" but isn't there a "hidden" param I can use to access the lexical vars of the caller/consumer scope?

No, this is not possible.

The lexical scope is resolved during the compile time. The method is written in generic way and can be technically called from anywhere. Therefore compiler cannot guess the lexical scope of all potential calls.

The only way, if you want to maintain separate method, is to wrap the call into wrapping lambda and pass the local variable as a parameter. But I assume this wasn't original goal.

No, you can't create a regular method that has access to local variables outside of the method.

The name of lambdas keeping copies of local variables from the scope in which it is defined is closure .

The only other way that I know of using closures in Java is anonymous inner classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM