Functions and Records
Arrow Functions
=> Shorthand
When a function's body is a single expression, => is shorthand for { return expr; }. The block form and the arrow form behave identically; arrow is just more concise.
Program
Play the program to call a block-body and an arrow-body version of the same idea.
arrow_functions.dart
Replay: real traced execution (multi-file project)
int squareBlock(int n) {
return n * n;
}
int squareArrow(int n) => n * n;
void main() {
var a = squareBlock(5);
var b = squareArrow(6);
print('$a $b');
}
call ← squareBlock(5)
7void main() {8 var a = squareBlock(5);9 var b = squareArrow(6);values this stepsquareBlock(5)callreturn value ← 25
1int squareBlock(int n) {2 return n * n;3}values this step25return value5na ← 25
7void main() {8 var a = squareBlock(5);9 var b = squareArrow(6);values this step25acall ← squareArrow(6)
8var a = squareBlock(5);9var b = squareArrow(6);10print('$a $b');values this stepsquareArrow(6)callreturn value ← 36
5int squareArrow(int n) => n * n;values this step36return value6nb ← 36
8var a = squareBlock(5);9var b = squareArrow(6);10print('$a $b');values this step36bprint('$a $b');
9 var b = squareArrow(6);10 print('$a $b');11}output25 36values this step25a36b
arrow body
`fn(x) => expr` is shorthand for `{ return expr; }` when the body is one expression.
implicit return
There is no `return` keyword in an arrow body; the expression's value is returned.
equivalent semantics
Block-body and arrow-body produce the same call result; arrow is just terser.