Lambda Expressions:Best Practices java 8_PART5

preview_player
Показать описание
In this video tutorial you will learn about the Lambda Expressions:Tips and Best Practices.
Below is the GitHub link to download source Code:
Рекомендации по теме
Комментарии
Автор

There are two different rules about final or effectively final variable use in a lambda.
1. Any local variables referenced in a lambda must be final or effectively final. If anyone, either inside the lambda or outside of it, re-assigns the value while the lambda is in scope, your code will not compile.
2. You may not declare a new variable of the same name as any local variable in scope where the lambda is defined within your lambda, nor may you use such a variable name as a parameter for the lambda.
The 819 certification exam seems to LOVE giving you questions on these.
What you showed violates Rule #2, and gives the error:
Lambda expression's local variable localVariable cannot redeclare another local variable defined in an enclosing scope. (This is what it looks like when you violate Rule #2 which you did not mention explicitly).
The following code illustrates violating the first rule:
private void method()
{
String localVariable = "Local";
Function<String, String> fun = s -> {
localVariable = s;
return localVariable;
};
}
Local variable localVariable defined in an enclosing scope must be final or effectively final

Also, so does this, because the localVariable is no longer "effectively final" despite only being read by the lambda:
private void method()
{
String localVariable = "Local";
Function<String, String> fun = s -> {
return localVariable;
};
localVariable += "Ouch!";
}
Both rules are important for anyone taking the cert exam.

jvsnyc