June 2018
Intermediate to advanced
280 pages
7h 46m
English
Closure is a technique to implement lexical scoping. Lexical scoping allows us to access the outer context variables inside the inner scope. Imagine that in our previous example the y variable had already been assigned a value. The lambda expression could remain a unary expression and still use the y as a variable. This could lead to some very hard-to-find bugs, as in the following code, where we would expect that the return value of our function remains the same. The closure captures the current value of an object, as we can see in the following code, where our expectation is that the add100 function will always add 100 to the given input, but it does not:
jshell> Integer a = 100a ==> 100jshell> Function<Integer, Integer> add100 ...
Read now
Unlock full access