dart 函数 - 箭头语法冲突

dart function - arrow syntax confliction

1。 Dart Language tour 有冲突

在函数部分,它说

The => expr syntax is a shorthand for { return expr; }.

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.

但是在匿名函数部分,它说

If the function contains only one statement, you can shorten it using arrow notation

这是否意味着我可以在匿名函数中使用不是表达式的语句(例如 if 语句)?

var fun = () => return 3; // However, this doesn't work.
var gun = () {
  return 3;               // this works.
}

还是我混淆了表达式和语句的概念?我以为

2。这是表达式还是语句

void foo() => true; // this works.
void goo() {
  return true;      // this doesn't work.
}
void hoo() {
  true;             // this works.
}

如果 true 被理解为表达式,那么它将表示 return true 并且我认为它不应该起作用,因为 foo 的 return 类型是 void。

那么foo中的true是不是理解为一个语句呢?但是这个结论和dart语言之旅是矛盾的。 (它们是顶级命名函数)。此外,这意味着我们可以使用带有箭头语法的语句。


我使用 VSCode 和来自 flutter 的 Dart:1.22.5。我根据 VSCode 错误消息告诉代码从不工作的代码开始工作。

因为这是我的第一个问题,对于我简短的英语和错误的问题,我深表歉意。

我猜匿名函数下那部分的作者有点困惑。针对它提出问题,并对其进行更正!

是的,即使在他们的示例中,他们也使用了 print() 函数,他们可能会将其混淆为打印“语句”,但显然不是。

必须是表达式。文字具有误导性。

对于第二部分,您看到的错误是

void foo() {
  return 0;
}

而不是

void bar() => 0;

是函数 returning void=> 特例 。通常情况下,您不能 return 来自具有 return 类型 void 的函数的 ,因此没有 return exp;,只有 return;。 (如果 exp 的类型为 voidnulldynamic,则有例外,但你的没有)。

因为人们非常喜欢 void foo() => anything; 的简写符号,所以无论 anything 是什么类型,您都可以这样做。这就是 void foo() { return 0; }void foo() => 0; 之间存在区别的原因。他们仍然是同一件事,但是前者的基于类型的错误在后者中被故意抑制了。