What is 'Closure' in Functions?

Viewed 345

I am right now learning a beautiful programming language, Dart, which I am loving so much. However, I am finding my basic programming knowledge has some gaps, and one of them is 'Closure' in Functions which I am finding difficult to understand. Can you please explain to me what is unique from Anonymous Function??

1 Answers

"Closure" is a word that is used about many different things.

Generally, and originally, a closure is a (function) value which contains references to variables (it "closes over" those variables).

In Dart, you can introduce functions in two different ways.

  • A function declaration: int foo(int x) => x; (as a top-level, static - if prefixed by static, instance or local function).
  • A function expression: (int x) => x (as an expression).

The first function is named, and can be called by name, referring directly to the declaration (foo(42)). It can also be turned into a function value by "tearing off" the function:

int Function(int) f = foo;

A function expression evaluates to a function value directly.

int Function(int) f = (int x) => x;

A lot of people use the word "closure" about function values, also called "first class function values" because they are objects like any other object, not special second-class values that can only be used in limited ways. If you see someone saying "closure", assume that's what they mean - an object which is also a function.

Technically, the function values here do not close over any variables. An example of one which does would be:

int Function(int) adder(int base) => (int addition) => base + addition;
int Function(int) add2 = adder(2);

The function value stored in the add2 variable here is the value of the function expression (int addition) => base + addition. The base variable is not bound by this expression, it is instead captured/"closed over" by the closure/function value. The base variable being closed over here comes from the invocation of adder with the value 2.

Related