dart:类构造函数被标记为const的含义是什么

时间:2015-03-11 09:01:29

标签: dart

所以我看过这样的代码:

class Whatever {
  final String name;
  const Whatever(this.name);
}

构造函数标有const的事实会改变什么?它有任何影响吗?

我读过这个:

  

对要成为编译时常量的变量使用const。如果   const变量在类级别,将其标记为静态const。   (实例变量不能是常量。)

但是对于类构造函数似乎没有意义。

2 个答案:

答案 0 :(得分:4)

  • 构造函数不能有构造函数体。
  • 所有成员必须是最终成员,必须在声明或构造函数参数或初始化列表中初始化。
  • 您可以使用此类的实例,其中只允许使用常量(注释,可选参数的默认值,...)
  • 您可以创建static const someName = const Whatever();
  • 等常量字段

如果类没有const构造函数,则不能用它来初始化常量字段。我认为在构造函数中指定它是有意义的。您仍然可以使用new Whatever()在运行时创建实例,或者添加工厂构造函数。

另见

"旧式" (仍然有效)枚举是一个很好的例子,如何使用const https://stackoverflow.com/a/15854550/217408

答案 1 :(得分:1)

如果您的类产生永远不会改变的对象,您可以将这些对象设为编译时常量。为此,请定义一个 const 构造函数并确保所有实例变量都是最终变量。

class ImmutablePoint {
  const ImmutablePoint(this.x, this.y);

  final int x;
  final int y;

  static const ImmutablePoint origin = ImmutablePoint(0, 0);
}

代码示例

修改 Recipe 类使其实例可以是常量,并创建一个执行以下操作的常量构造函数:

  • 具有三个参数:ingredients, caloriesmilligramsOfSodium(按此顺序)。

  • 使用 this。自动将参数值分配给同名对象属性的语法。

  • 是常量,在构造函数声明中 const 前有 Recipe 关键字。

    class Recipe {
      final List<String> ingredients;
      final int calories;
      final double milligramsOfSodium;
    
      const Recipe(this.ingredients, this.calories, this.milligramsOfSodium);
    }