【问题标题】:should returning const value from const object be const?从 const 对象返回的 const 值应该是 const 吗?
【发布时间】:2013-03-30 13:42:44
【问题描述】:

我正在使用下面的样式类来模仿枚举(来自Does Dart support enumerations?) 它运行良好,因为这个 sn-p 产生了预期的结果。

void main() {
  InterpolationType it = InterpolationType.LINEAR;
  print("it is $it and stringified ${stringify(it)}");
  print(InterpolationType.fromJson(it.toJson()));
}

但是 DartEditor 在 fromJson 方法的 case 语句中抱怨“预期的常量表达式”。我可以在某个地方添加一个 const 来摆脱这种抱怨吗?

class InterpolationType { 
  static const LINEAR = const InterpolationType._(0);
  static const STEP = const InterpolationType._(1);
  static const CUBIC = const InterpolationType._(2);

  static get values => [
    LINEAR,
    STEP,
    CUBIC
  ];

  final int value;

  const InterpolationType._(this.value);

  String toString() { 
    switch(this) { 
      case LINEAR: return "LINEAR";
      case STEP: return "STEP";
      case CUBIC: return "CUBIC";
    }
  }

  int toJson() { 
    return this.value;
  }

  static InterpolationType fromJson(int v) { 
    switch(v) { 
      case LINEAR.value: return LINEAR;
      case STEP.value: return STEP;
      case CUBIC.value: return CUBIC;
    }
  }

  static InterpolationType fromString(String s) { 
    switch(s) { 
      case "LINEAR": return LINEAR;
      case "STEP": return STEP;
      case "CUBIC": return CUBIC;
    }
  }
}

【问题讨论】:

    标签: dart


    【解决方案1】:

    正如您所发现的:从 const 对象访问字段并不是一个常量操作。所以编辑器(以及VM和dart2js)是对的。

    使用当前的语法,没有办法表达一个(非正式的)约定,即类的字段将始终是最终字段。例如,我可以将 value-field 更改为 getter 而不是字段。类的接口契约绝对允许我这样做,因为我从未告诉任何人我会将“价值”作为一个字段。但是,如果我这样做,它会破坏所有依赖这个 final 字段存在的程序。

    因此,当前的行为不太可能改变。

    但是:理论上可以改进 Dart 语言,以便您可以对本地字段使用“const”而不是“final”,并使用初始化列表对其进行初始化。在这种情况下,访问该字段可以被认为是一个常量操作。我目前看不出这种行为有任何不利之处,而且它是向后兼容的。

    // WARNING: What follows DOES NOT WORK, just a potential example
    class InterpolationType {
      const value;  // Note the "const" instead of "final".
      const InterpolationType._(this.value);
    }
    

    该语言已经相当稳定,但您可以在 http://dartbug.com/ 打开一个错误并建议这种行为。功能请求被接受的可能性不大,但绝对值得一试。

    【讨论】:

    • 如果我理解,建议是将“最终 int 值”更改为“常量值”。对上面的示例执行此操作会给出:错误:第 15 行 pos 9:const field 'value' must have an initializer expression
    • 正确。这种行为还不存在。您可以将其建议为该语言的功能请求。 (改写答案以明确这一点)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 2012-11-07
    • 2018-06-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多