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
makeCounterreturns a function closing overseen.- Each call through
logincrements the captured counter. int Function(int)types a function parameter inline.
Keywords and builtins used here
FunctionStringfinalintreturnvarvoid
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.
Step 2 of 3 in Functions, step 8 of 27 in Language basics.