Using lambdas causes strange “variable X might not have been initialized” error

It’s been long time since Java 8 became publicly available but it is still surprising me a lot. Its spec is definitely worth reading. One of the things I recently stumbled upon is the fact that lambdas are not the same as anonymous classes. A compilation error reproducible only when building with maven was bugging me for some time. In eclipse everything was just fine while Jenkins showed a red status. I got something like “variable X might not have been initialized”. Strange I said but then looking into specs I found the answer:

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).

Would you expect that? In my case I had a panel which creates some controls including buttons and adds listeners to them. One of the listeners was using a control created later in the code. This is usually not a problem since a reference to this control is stored in a fieldĀ andĀ all listeners are executed much later when the panel is fully created. Anonymous classes work just fine in this case but lambdas give a compilation error. It is obviously because the lambda’s body is treated as it was a part of the surrounding context.

Share on FacebookShare on LinkedInShare on Google+Tweet about this on TwitterPin on PinterestShare on RedditDigg this

Vitaly Tsaplin

Hey, I am Vitaly and this is my blog. I live in Basel and work at Adobe.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Leave a Comment

Time limit is exhausted. Please reload CAPTCHA.