Help Us Improve. Please let us know if you were asked any of these questions.

More Questions

ERROR - Local variable defined in an enclosing scope must be final or effectively final

Error

Local variable <checkAgainstNumber> defined in an enclosing scope must be final or effectively final


while using Lambda Expressions in Java 8.


Error Type


Compile Time


Sample Code


Set<Integer> intSet = new HashSet<Integer>();
intSet.add(1);

intSet.add(2);
int checkAgainstNumber = 2;
checkAgainstNumber = 5;  
Predicate<Integer> moreThan2Pred = (p) -> (p > checkAgainstNumber);

Cause

Local Variable used within lambda expression is not effective final. Variables that are used within scope of Lambda expressions should be either final or effective final i.e shouldn't be changed after initialization.


Resolution 


Either declare the used variable as final and don't reassign the value.

Set<Integer> intSet = new HashSet<Integer>();
intSet.add(1);

intSet.add(2);
final int checkAgainstNumber = 2; 
Predicate<Integer> moreThan2Pred = (p) -> (p > checkAgainstNumber);

or

Don't reassign the variable value and let it be effective final.

Set<Integer> intSet = new HashSet<Integer>();
intSet.add(1);

intSet.add(2);
int checkAgainstNumber = 2; 
Predicate<Integer> moreThan2Pred = (p) -> (p > checkAgainstNumber);

 Stay Updated with Java Posts directly to your mailbox.
Enter your email address:

'
Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


×

Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.