Self-reference to field from lambda expression in initializer

Markus Keller markus_keller at ch.ibm.com
Tue Dec 3 02:11:55 PST 2013


JLS7 8.3.2.3 "Restrictions on the use of Fields during Initialization" 
says as point 4: "C is the innermost class or interface enclosing the 
usage".

This should be expanded to include lambda bodies, e.g.:
"C is the innermost class or interface enclosing the usage, or the usage 
occurs inside a lambda expression body that occurs in the initializer".

The informative text later in that section confirms this intention:
"The restrictions above are designed to catch, at compile time, circular 
or otherwise malformed initializations."

In case of lambda bodies, self-references don't cause malformed 
initializations, so this restriction is not necessary. It would make sense 
to handle self-references in lambda expressions the same as in anonymous 
classes.

Example that shows that javac only disallows unqualified access as per 
8.3.2.3:

public class C {
    // javac 1.8.0-ea-b115 says: error: self-reference in initializer
    Runnable i= () -> executeAndRepost(i);
    static Runnable s= () -> executeAndRepost(s);
 
    // OK:
    Runnable qi= () -> executeAndRepost(this.qi);
    static Runnable qs= () -> executeAndRepost(C.qs);
    Runnable a= new Runnable() {
        @Override public void run() {
            executeAndRepost(a);
        }
    };
 
    static void executeAndRepost(Runnable r) { }
}



More information about the lambda-spec-comments mailing list