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');
}
  1. fn ← <function square>

    8void main() {9  int Function(int) fn = square;10  var first = transform(4, fn);
    values this step<function square>fn
  2. call ← transform(4, square)

    9int Function(int) fn = square;10var first = transform(4, fn);11fn = negate;
    values this steptransform(4, square)call<function square>fn
  3. calls ← 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>f
  4. return value ← 16

    5int square(int n) => n * n;6int negate(int n) => -n;
    values this step16return value4n
  5. return value ← 16

    1int transform(int x, int Function(int) f) {2  return f(x);3}
    values this step16return value
  6. first ← 16

    9int Function(int) fn = square;10var first = transform(4, fn);11fn = negate;
    values this step16first
  7. fn ← <function negate>

    10var first = transform(4, fn);11fn = negate;12var second = transform(4, fn);
    values this step<function square> <function negate>fn
  8. call ← transform(4, negate)

    11fn = negate;12var second = transform(4, fn);13print('$first $second');
    values this steptransform(4, negate)call<function negate>fn
  9. calls ← 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>f
  10. return value ← -4

    5int square(int n) => n * n;6int negate(int n) => -n;
    values this step-4return value4n
  11. return value ← -4

    1int transform(int x, int Function(int) f) {2  return f(x);3}
    values this step-4return value
  12. second ← -4

    11fn = negate;12var second = transform(4, fn);13print('$first $second');
    values this step-4second
  13. print('$first $second');

    12  var second = transform(4, fn);13  print('$first $second');14}
    output16 -4
    values 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.