Why should lambda parameters overshadow enclosing variables?

When you write a lambda expression, you (usually) define the parameter names as indicators of how the values assigned to them should be processed. They aren't meant to reuse the existing values, referred to by variables, in an enclosing block.

Let's revisit the preceding code:

1. String key = "Docker"; // local variable key
2. talks.stream()
3. .map(key -> key.toUpperCase()) // WON'T compile : 'key'
// redefined
4. .forEach(System.out::println);

In the preceding code, the lambda expression on line 3 (in bold) defines one lambda parameter, key, specifying that when a value is passed to it, Java should call the toUpperCase() method on it and return the resulting value.

As is evident from this example, the key lambda parameter appears to be unrelated to the local key variable, defined in the enclosing block. So, the lambda parameters should be allowed to overshadow the variables with the same names in the enclosing block.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.198.174