我知道 const 是 dart 中的编译时常量,但我不明白以下代码中const [F0, F1, F2]
背后的机制:
class Foo {
static const F0 = 'F0';
static const F1 = 'F1';
static const F2 = 'F2';
// const list of const values I guess...
static const CONST_LIST = const [F0, F1, F2]; // please explain this line
static final String FOO = CONST_LIST[0]; // ok
// compile error: 'const' varaibles must be constant value
// static const String BAR = CONST_LIST[1];
}
main() {
// is CONST_LIST const or not?
// below line it's ok for dartanalyzer but
// in runtime: Cannot change the content of an unmodifiable List
Foo.CONST_LIST[1] = 'new value';
}
我注意到 const
是 const [F0, F1, F2];
中的 dart 分析器所必需的,但它确实使列表更像最终(运行时不可变列表)而不是编译时常量。
更新:
另一个问题是为什么CONST_LIST[1]
不是"常量值"。请参阅Foo.BAR
的注释声明。
Günter已经回答了你问题的第二部分。以下是有关 const 的更多信息。
Const意味着对象的整个深层状态可以在编译时完全确定,并且对象将被冻结并且完全不可变。
本文中的详细信息。另请参阅以下问题。
关于问题的第二部分,请考虑以下几点:
const int foo = 10 * 10;
表达式 "10 * 10" 可以在编译时计算,因此它是一个"常量表达式"。在常量表达式中可以执行的操作类型需要非常有限(否则您可以在编译器中运行任意 Dart 代码!但是随着飞镖的成熟,其中一些限制正在放松,正如你在Günter链接到的错误中看到的那样。
相反,请考虑以下事项:
final int bar = 10;
final int foo = bar * bar;
由于"bar * bar"不是常量表达式,因此在运行时对其进行计算。
有一个开放的错误:见 https://github.com/dart-lang/sdk/issues/3059