dart中`const ['foo','bar']`中const的含义

时间:2014-11-16 13:49:07

标签: dart const constants

我知道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中的dart分析器需要const [F0, F1, F2];,但它确实使列表更像final(运行时不可变列表)而不是编译时间const。

更新

另一个问题是为什么CONST_LIST[1]不是“恒定值”。请参阅Foo.BAR的注释声明。

2 个答案:

答案 0 :(得分:3)

Günter已经回答了你问题的第二部分。以下是有关const的更多信息。

  

Const意味着可以在编译时完全确定对象的整个深度状态,并且该对象将被冻结并完全不可变。

article中的更多信息。另请参阅以下question

关于问题的第二部分,请考虑以下事项:

const int foo = 10 * 10;

表达式“10 * 10”可以在编译时进行评估,因此它是一个“常量表达式”。您可以在常量表达式中执行的操作类型非常有限(否则您可以在编译器中运行任意Dart代码!)。但随着飞镖成熟,这些限制中的一些正在放松,正如您可以在Günter链接的错误中看到的那样。

相反,请考虑以下因素:

final int bar = 10;
final int foo = bar * bar;

由于“bar * bar”不是常量表达式,因此在运行时进行评估。

答案 1 :(得分:2)

这是一个开放的错误:请参阅https://github.com/dart-lang/sdk/issues/3059

相关问题