Given the following class, Dart Editor (build 5549) gives me some conflicting feedback (per the comments in the constructor body):

class Example {
  final int foo;

  Example() :
    foo = 0
  {
    foo = 1; // 'cannot assign value to final variable "foo"'
    this.foo = 2; // ok
  }
}

Even more confusingly, it will happily generate equivalent (working) javascript for both lines. The situation seems to be the same with methods as it is with the constructor; this especially leads me to believe that it was intended to be disallowed in both cases.

The Dart Style Guide suggests using public final fields instead of private fields with public getters. I like this in theory, but non-trivial member construction can't really go into the initializer list.

Am I missing a valid reason for the former to be reported as an error while the latter is not? Or should I be filing a bug right now?

有帮助吗?

解决方案

This is surely a bug in the JavaScript generator if you run the following in the Dart VM:

main() {
  new Example();
}

class Example {
  final int foo;

  Example() : foo = 0 {
    foo = 1;      // this fails in the dart vm
    this.foo = 2; // this also fails in the dart vm
  }
}

then it refuses to execute both the line foo = 1 and this.foo = 2. This is consistent with the spec which requires (if I read it correctly) that final fields to be final in the constructor body.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top