Functions and Records
Higher-Order Functions
Passing a Function
A function can take another function as an argument and call it inside. The parameter type int Function(int) describes the expected callback shape, and a function variable can point at different compatible functions over time.
Program
Play the program to pass two different callbacks through the same transform function.
higher_order.dart
Replay: real traced execution (multi-file project)
int transform(int x, int Function(int) f) {
return f(x);
}
int square(int n) => n * n;
int negate(int n) => -n;
void main() {
int Function(int) fn = square;
var first = transform(4, fn);
fn = negate;
var second = transform(4, fn);
print('$first $second');
}
fn ← <function square>
8void main() {9 int Function(int) fn = square;10 var first = transform(4, fn);values this step<function square>fncall ← transform(4, square)
9int Function(int) fn = square;10var first = transform(4, fn);11fn = negate;values this steptransform(4, square)call<function square>fncalls ← f(4) -> square(4)
1int transform(int x, int Function(int) f) {2 return f(x);3}values this stepf(4) -> square(4)calls4x<function square>freturn value ← 16
5int square(int n) => n * n;6int negate(int n) => -n;values this step16return value4nreturn value ← 16
1int transform(int x, int Function(int) f) {2 return f(x);3}values this step16return valuefirst ← 16
9int Function(int) fn = square;10var first = transform(4, fn);11fn = negate;values this step16firstfn ← <function negate>
10var first = transform(4, fn);11fn = negate;12var second = transform(4, fn);values this step<function square> → <function negate>fncall ← transform(4, negate)
11fn = negate;12var second = transform(4, fn);13print('$first $second');values this steptransform(4, negate)call<function negate>fncalls ← f(4) -> negate(4)
1int transform(int x, int Function(int) f) {2 return f(x);3}values this stepf(4) -> negate(4)calls4x<function negate>freturn value ← -4
5int square(int n) => n * n;6int negate(int n) => -n;values this step-4return value4nreturn value ← -4
1int transform(int x, int Function(int) f) {2 return f(x);3}values this step-4return valuesecond ← -4
11fn = negate;12var second = transform(4, fn);13print('$first $second');values this step-4secondprint('$first $second');
12 var second = transform(4, fn);13 print('$first $second');14}output16 -4values this step16first-4second
function value
`fn = square` and `fn = negate` store functions themselves; no call happens until `fn(...)` is used.
function-type parameter
`int Function(int) f` declares a parameter whose value is a function from `int` to `int`.
callback
`f(x)` inside `transform` runs whichever function was passed in.