Arrow functions
- Dart course
- Beginner
- Lesson 67/116
- 5 min
Learn to write short functions with =>.
Arrow functions
The arrow function is a short way to write single-expression functions. The => operator puts the body on one line. Example: int square(int n) => n * n;.
This is fully equivalent to int square(int n) { return n * n; }. The expression after the arrow is returned automatically; you do not write return.
An arrow function can hold only one expression; if you need more statements, use the curly-brace form. It is ideal for short transforms and computations.
Arrow versus classic
The same function can be written in two forms. Classic: int double(int n) { return n * 2; }. Arrow: int double(int n) => n * 2;. Both do the same thing.
The arrow form drops return; the expression returns by itself. The classic form requires return; the compiler complains otherwise.
Pick based on body length: a single line suits the arrow, several statements need curly braces. They read side by side; the Dart community prefers the arrow for short functions.
Practice Double with the arrow
Define a twice(int n) arrow function whose body is n * 2. Add a print(twice(21)) call inside main.
Starter code
void main() {
// define the twice arrow function
// print the result
}Sample solution
int twice(int n) => n * 2;
void main() {
print(twice(21));
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write it with the arrow
int square(int n) ____ n * n;
int square(int n) => n * n;
Explanation: => is the arrow function operator.
2 return in an arrow function?
- Not written, returns automatically Correct answer
- Required and written
- Only in void
- Throws an error
Explanation: arrow functions have no return; the expression returns on its own.
3 Match the forms
| Term | Meaning |
|---|---|
int square(int n) { return n*n; } |
Classic form |
int square(int n) => n * n; |
Arrow form |
return |
Required in classic |
=> |
Arrow symbol |