0

Why doesn't constructor syntactic sugar for setting fields work when importing fields from a mixin?

mixin Nameable { 

  var name = '';

}

class Person with Nameable {

  Person(this.name);

}

Fails with error-message 'name' isn't a field in the enclosing class.

This is ok though

mixin Nameable { 

  var name = '';

}

class Person with Nameable {

  Person(String name) {
    this.name = name;
  }

}

Report as a bug?

MendelG
  • 14,885
  • 4
  • 25
  • 52
weenzeel
  • 797
  • 5
  • 17
  • 1
    The two aren't actually equivalent. The `Person(this.name);` syntactic sugar is equivalent to `Person(String name) : name = name;`, and initialization lists are processed *before* constructing base classes. [The constructor body executes in a different phase of object construction](https://stackoverflow.com/a/63319094/), *after* constructing base classes. – jamesdlin Dec 17 '20 at 21:55
  • Thanks for pointing out the difference! – weenzeel Dec 18 '20 at 17:28

1 Answers1

1

Initializing formals, and initializer list entries, in generative constructors can only initialize fields which are declared in the same class.

A field introduced by a mixin, like here, is not declared in the class. It's mixed into a mixin application class, Object with Namable, which becomes the superclass of Person.

Assigning to the field in the body of a constructor is just normal assignment, not initialization. It wouldn't work if you wanted the field to be final.

lrn
  • 64,680
  • 7
  • 105
  • 121