Lexical Closures
A closure is a function object that has access to variables in its lexical scope, even when the function is used outside of its original scope.
Functions can close over variables defined in surrounding scopes.
//returns a function that adds x to the function's argument
Function createAdder(int x) {
return (int y) {
return x + y;
};
}
//returns a function that multiply x to the function's argument
Function createMultiplier(int x) {
return (int y) => x * y;
}
void main() {
var add10 = createAdder(10);
var add5 = createAdder(5);
print(add10(7));
print(add5(9));
var multiplyBy2 = createMultiplier(2);
var muuliplyBy5 = createMultiplier(5);
print(multiplyBy2(4));
print(muuliplyBy5(3));
}
17
14
8
15
14
8
15