Learning Dart as a JavaScript developer
JavaScript 和 Dart 都支持箭头语法,但不同之处在于, Dart 仅在函数只含有单个表达式或者语句时才允许使用,JavaScript 则不受限制。
bool isNoble(int atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
等价于:
bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;
Stack Overflow
For functions that contain just one expression, you can use a shorthand syntax. The =>
expr syntax is a shorthand for { return expr; }
. The =>
notation is sometimes referred to as arrow syntax.
Note: Only an expression—not a statement—can appear between the arrow (=>
) and the semicolon (;
). For example, you can’t put an if statement there, but you can use a conditional expression.
int sum(int x, int y) {
return x + y;
}
等价于:
int sum(int x, int y) => x + y;