Dart 中表达式和语句的区别?

Difference between an Expression and Statement in Dart?

由于不同的语言对表达式和语句的定义不同,那么它们在Dart中有什么区别?

我对 Dart 还是个新手,但我有以前的知识(并阅读了 dart 语言之旅):

  • 表达式 通常求值,例如当使用条件表达式时,condition ? expr1 : expr2 的值为 expr1expr2
  • 语句没有任何价值,或者通常不做任何直接改变值的事情。

一个statement包含expressions,但是一个expression不能包含一个statement.

以上是我对要点的解释,我试图为你简化,阅读language tour on category important concepts时发现是这样的:

Dart has both expressions (which have runtime values) and statements (which don’t). For example, the conditional expression condition ? expr1 : expr2 has a value of expr1 or expr2. Compare that to an if-else statement, which has no value. A statement often contains one or more expressions, but an expression can’t directly contain a statement.

来自维基百科:

In mathematics, an expression or mathematical expression is a finite combination of symbols that is well-formed according to rules that depend on the context. Mathematical symbols can designate numbers (constants), variables, operations, functions, brackets, punctuation, and grouping to help determine order of operations, and other aspects of logical syntax.

在 Dart 中也是如此。

这种情况下的语句可以描述为表达式和可能的其他符号的组合,这些符号是正确表示具体语句所需的。

在Dart中,语句可以为空,即语句不包含任何表达式。空语句可以用格式正确的符号表示或由上下文确定。

if-else 语句的示例(伪代码)。

if (expression) { statement(s) } else { statement(s) }

简答

表达式是,语句做事

例子

如果你能看到例子,这就更有意义了。

表达式

表达式在运行时有值。

  • 42
  • true
  • hello
  • 1 + 1
  • x
  • myObject
  • myInt + 1
  • k++
  • p > 0
  • condition ? expr1 : expr2
  • 'hello'.toUpperCase()
  • myObject.toString()
  • myObject.someMethod()
  • myObject?.someProperty?.someMethod()
  • myString.isEmpty
  • [1, 2, 3]
  • [...list1]
  • <String, String>{...a, ...b}

声明

一个语句做一些事情,它本身在运行时没有价值。语句不是表达式,但可以包含表达式。

  • myInt = 1;
  • print('hello');
  • return null;
  • if (name != null) { return name; } else { return 'Guest'; }
  • for (var i = 0; i < 5; i++) { message.write('!'); }
  • break;
  • while (!isDone()) { doSomething(); }
  • yield k++;
  • assert(text != null);
  • throw FormatException('Expected at least 1 section');
  • void distanceTo(Point other) => throw UnimplementedError();

Note: Most of the examples here came by searching the documentation for the keywords expression and statement.