lambda – final local var — rationales, loopholes

Possibly a popular interview question…..

For Both lambda and inner classes to use a given variable:

A) local vars in enclosing method must be (as of Java 8, "effectively") final
** subversion / loophole — a final local variable in the form of "array of 1" would let the lambda to modify the content
**** similarly, you can provide a wrapper object, who is a final local variable but not immutable.
B) enclosing Class instance fields don’t need finality to be usable in lambda.

The most important motivation for the (effective) finality restriction is thread safety. For (B), this restriction is impractical.

Incidentally (perhaps another post), in java 8, you lambda is compiled not as an inner class, but as a static method with a special helper class.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s