Java Reference
In-Depth Information
// Here, this refers to the current object of the
// anonymous class
System.out.println(msg + ": " + this.getClass());
}
};
return printer;
}
}
getLambdaPrinter(): class com.jdojo.lambda.ScopeTest
Lambda Expressions: class com.jdojo.lambda.ScopeTest
getAnonymousPrinter(): class com.jdojo.lambda.ScopeTest
Anonymous Class: class com.jdojo.lambda.ScopeTest$1
Lexical scoping of a lambda expression means that variables declared in the lambda expression, including its
parameters, exist in the enclosing scope. Simple names in a scope must be unique. It means that a lambda expression
cannot redefine variables with the same name that already exist in the enclosing scope.
The following code for a lambda expression inside a method generates a compile-time error as its parameter
name msg is already defined in the method's scope:
public class Test {
public static void main(String[] args) {
String msg = "Hello";
// A compile-time error. The msg variable is already defined and
// the lambda parameter is attempting to redefine it.
Printer printer = msg -> System.out.println(msg);
}
}
The following code generates a compile-time error for the same reason that the local variable name msg is in
scope inside the body of the lambda expression and the lambda expression is attempting to declare a local variable
with the same name msg :
public class Test {
public static void main(String[] args) {
String msg = "Hello";
Printer printer = msg1 -> {
String msg = "Hi"; // A compile-time error
System.out.println(msg1);
};
}
}
 
Search WWH ::




Custom Search