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);