Skip to content

Value fields #3332

@leafpetersen

Description

@leafpetersen

Field reads cannot in general be promoted based on null checks or instance checks because stability of the result cannot be guaranteed. Older overview summary here. Various proposals have been floated to resolve this based on either providing a way for APIs to opt into promotion (e.g. stable getters) or by providing better ways to bind a local variable (search for the label field-promotion for some discussion issues).

This issue sketches out an approach based on adding a new modifier on fields which enforces that the field has value semantics (in the sense that a read of the field is guaranteed to be idempotent). This is enforced by disallowing overriding a value field with a getter.

To enforce this, we add a new member modifier val which can be used to modify a field in place of final.

class A {
   val int x;
   A(this.x);
}

A val field has the same semantics as a final field, with the following modification:

  • It is a static error to override or implement a val field with anything other than another val field.
  • It is a static error to override or implement a val field with a noSuchMethod forwarder.

As with final fields, a val field may be declared late.

A val field may implement/override a final field or a getter.

A read of a val field is subject to promotion.

cc @dart-lang/language-team

Metadata

Metadata

Assignees

No one assigned

    Labels

    field-promotionIssues related to addressing the lack of field promotion

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions