Learnitweb

Local variables referenced from a lambda expression must be final or effectively final

As per Java 8 Language Specification:

Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

A variable which is not declared as final but whose value is never changed after initialization is effectively final.

In the following code, lambda expression uses local variable ‘score’. In this case, score is ‘effectively final’. Any attempt to reassign value to ‘score’ will result in compile-time exception – ‘Local variable score defined in an enclosing scope must be final or effectively final’.

interface Playable{
	public void play();
}

public class Test {
	public void testMethod() {
		int score = 100;
		Playable p = () -> {
			//score = 101;    //This is not allowed as 'score is effectively final'
			System.out.println("Play with score " + score);
		};
		//score = 101;    //This is not allowed as 'score is effectively final'
		p.play();
	}
	public static void main(String args[]) {
		Test t = new Test();
		t.testMethod();
	}
}