public class TrickyLambdaExpressionDemo {
public static void main(String …args){
String name = “Hello World”;
Runnable r1 = ()-> System.out.println(name);

String name1 = “”;
name1 = name.toUpperCase();
Runnable r2 = ()-> System.out.println(name1);

r1.run();
}
}

What will be the result, if you run the above code?

The answer is “Compile Error”. The error is “Variable used in Lambda expression must be effectively final”.

If you change it to

String name1 = name.toUpperCase();

Then it will print out “Hello World”

Another point we should pay attention to is the word “effectively final” what is the difference between final and effectively final?

I always think lambda expression is a kind of anonymous class. In Java any local variable within an anonymous class should be final! Thus it is reasonable lambda expression requires variable to be final. But why effectively final? it means although the developer does not put the keyword final in front of the variable, in the above sample it is name1, if once it has been initialised,  the value never changed, the variable can be treated as final. This saves developer a lot of time to avoiding put the keyword final in front of any lambda variables.

Advertisements