First-class functions
- Dart course
- Beginner
- Lesson 69/116
- 5 min
Learn to pass functions as values.
First-class functions
In Dart functions are values: they can be assigned to a variable, passed as an argument, or returned. This is called being first-class.
Example: int Function(int) f = (n) => n * 2;. Here f holds a function; calling f(5) gives 10. The type int Function(int) reads 'function taking int, returning int'.
When a function is passed as an argument it is called a callback. For example apply(f, 5) takes a function and a value, applying the function to the value. This is the foundation of callbacks and higher-order functions.
Callbacks and higher-order
A function that takes another function as a parameter is called higher-order. Example: void apply(int Function(int) f, int x) { print(f(x)); }. It applies f to x and prints the result.
The function passed in is a callback. The caller invokes it when its work is done. List.map, List.forEach and similar Dart methods accept callbacks.
This pattern makes it easy to swap pieces: pass a different f to reuse the same apply. That cuts code repetition.
Practice The apply function
Define an apply higher-order function: void apply(int Function(int) f, int x). Its body should do print(f(x)). Add an apply((n) => n * 3, 5) call inside main.
Starter code
void main() {
// define the apply function
// add a call
}Sample solution
void apply(int Function(int) f, int x) {
print(f(x));
}
void main() {
apply((n) => n * 3, 5);
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does int Function(int) mean?
- A function returning int
- Two int params
- A function taking int and returning int Correct answer
- A list of int
Explanation: int Function(int) is the type of a function taking int and returning int.
2 Match the first-class concepts
| Term | Meaning |
|---|---|
int Function(int) |
Function type |
(n) => n * 2 |
Anonymous function |
f(5) |
Function call |
apply(f, 5) |
Higher-order call |
3 The function type
var f = (n) => n * 2;
int Function(int) g = ____;
var f = (n) => n * 2;
int Function(int) g = f;
Explanation: f is a function value and can be assigned.