你是否碰巧看到了Chris Strom关于常量构造函数的帖子?Chris Strom在文章中做的是对final字段的解释,但是向下滚动到评论部分,有一个对某个类的常量构造函数的很好的解释。
Const对象用在注释中:
import 'dart:mirrors';
class Foo{
final name;
const Foo(this.name);
}
@Foo("Bar")
class Baz{}
void main() {
ClassMirror cm = reflectClass(Baz);
print(cm.metadata.first.getField(#name).reflectee); // prints Bar
}
为什么引入const对象(来自开发团队):
为什么Dart有编译时间常量?
它们还可以提供额外的优化。例如,我的dar2js实验:
dart2js是否更好地优化了const对象?
一些细节:
class Foo{
final baz;
const Foo(this.baz);
}
void main() {
//var foo = const Foo({"a" : 42}); //error {"a" : 42} is a mutable Map
var foo = const Foo(const {"a" : 42}); //ok
//foo.baz["a"] = 1; //error Cannot set value in unmodifiable Map
var bar = new Foo({"a" : 42}); //ok
//bar.baz = {"c" : 24}; //error NoSuchMethodError: method not found: 'baz='
bar.baz["a"] = 1; //ok;
}
如果class只有const构造函数,您仍然可以使用new
创建可变对象,最终baz
是不可变引用。但是由于bar
是可变的,您可以更改baz
对象。