ximmyxiao
ximmyxiao

Reputation: 2817

How to distinguish the same variable name in dart constructor initializor list?

As the Container widget has a constraints instance variable 。 But the constructor will also has a constraints parameter.

And in the initializor list, We can see code like this:

constraints = (****) constraints;

So how do we know which constraints is reference to the instance variable , and which one is reference to the function parameter? enter image description here

Upvotes: 1

Views: 415

Answers (1)

jamesdlin
jamesdlin

Reputation: 90184

The name collision is not a problem in constructor initializer lists. The left-hand-side of each initialization may only be a member variable. From the Dart language specification:

Initializer Lists

An initializer list begins with a colon, and consists of a comma-separated list of individual initializers.

[...]

An initializer of the form v = e is equivalent to an initializer of the form this.v = e, both forms are called instance variable initializers.

Meanwhile, the expression on the right-hand-side cannot access this and therefore can never refer to a member variable. Therefore:

class Foo {
  int x;

  Foo(int x) : x = x;
}

has no ambiguity: the member variable x is initialized from the x parameter.

The name collision can be a problem in a constructor body, however:

class Foo {
  int x;

  Foo(int x) : x = x {
    x *= 10; // This modifies the local `x` parameter.
  }
}

In such cases, the constructor body must be careful to explicitly use this.x if it needs to use the member variable, not the parameter of the same name.

Upvotes: 3

Related Questions