typestar

Closures in Dart

Functions are values that remember the variables around them.

// Functions are values: pass them, return them, close over state.
Function makeCounter() {
  var seen = 0;
  return (String species) {
    seen += 1;
    return '#$seen: $species';
  };
}

void main() {
  final log = makeCounter();
  print(log('wren'));
  print(log('dunnock'));

  // A function parameter typed inline, applied by the caller.
  int apply(int n, int Function(int) f) => f(n);
  print(apply(6, (n) => n * n));
}

How it works

  1. makeCounter returns a function closing over seen.
  2. Each call through log increments the captured counter.
  3. int Function(int) types a function parameter inline.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
401
Tokens
106
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 91 seconds.

Type this snippet

Step 2 of 3 in Functions, step 8 of 27 in Language basics.

← Previous Next →

Closures in other languages