Skip to content

Shorthand constructor this.x parameters prohibit access to x in initializer list #1970

Closed
@sethladd

Description

@sethladd

This may be a known trade-off, but I was curious if this was a bug.

I tried to do:

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;
  
  Point(this.x, this.y) : distanceFromOrigin = calcDistance(x, y);
  
  static calcDistance(_x, _y) => Math.sqrt((_x*_x) + (_y*_y));
}

But the Editor (rightly so?) said "cannot access field in initializer expression". I understand 'this' isn't available in initializer lists, but I was a little surprised that I couldn't access the implicit x from the constructor parameter.

I ended up writing:

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;
  
  Point(x, y) :
    x = x,
    y = y,
    distanceFromOrigin = calcDistance(x, y);
  
  static calcDistance(_x, _y) => Math.sqrt((_x*_x) + (_y*_y));
}

Sounds like the tradeoff is "use the shorthand constructor parameter names or initializer lists"

Metadata

Metadata

Assignees

Labels

area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).closed-not-plannedClosed as we don't intend to take action on the reported issuetype-enhancementA request for a change that isn't a bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions