typedef
- Dart course
- Intermediate
- Lesson 70/116
- 5 min
Learn function types with typedef.
typedef for function types
A typedef gives a name to a function type. Instead of writing a long function type every time, you use a short name. For example typedef IntOp = int Function(int, int); creates a new type called IntOp.
You can use this type for a variable or a parameter: IntOp op = (a, b) => a + b;. You declare the signature once and reuse the same name everywhere.
A typedef only improves readability; it does not create a new runtime type. When the compiler sees IntOp it really means int Function(int, int).
Using a typedef
After you declare a typedef you can use it as a parameter type. For example void apply(IntOp op, int x, int y) => print(op(x, y)); accepts op as an IntOp.
So apply((a, b) => a * b, 3, 4) runs multiplication and prints 12. A typedef keeps signatures short in APIs that pass functions as parameters.
You can reuse the same typedef in many places; one change propagates everywhere.
Practice The MathOp typedef
Define typedef MathOp = int Function(int, int);. Write int add(int a, int b) => a + b;. In main assign add to a MathOp variable and print the result for 3 and 4.
Starter code
// Define the MathOp typedef (int Function(int, int))
// Write the add function
void main() {
// Assign add to a MathOp variable, print the result
}Sample solution
typedef MathOp = int Function(int, int);
int add(int a, int b) => a + b;
void main() {
MathOp op = add;
print(op(3, 4));
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does typedef do?
- Defines a new class
- Names a function type Correct answer
- Creates a new variable
- Starts a loop
Explanation: typedef names a function type.
2 The typedef keyword
____ IntOp = int Function(int, int);
typedef IntOp = int Function(int, int);
Explanation: the definition starts with the typedef keyword.
3 Match the typedef parts
| Term | Meaning |
|---|---|
typedef |
Definition keyword |
IntOp |
Type name |
int Function(int, int) |
Function type |
Function |
Function keyword |