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?