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
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');
}
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.