Skip to content

Allow const instance fields as const expressions on const objects. #16547

Open
@lrhn

Description

@lrhn

We currently disallow const on instance fields because we don't have a good semantics for them.

Consider allowing

class C {
  const int foo;
  const C(this.foo);
}

The instance const field will act just as a final field, except when initialized by a const invocation of a const constructor (i.e., except when on an actual compile-time constant).

Then we can allow expressions like x.foo to be compile time constant expressions if x is a compile time constant expression with a value that has a const instance field named foo.

This will allow changing a static-only class to an object, and still expose the same compile time constants.

Other uses could be an enum implementation that assigns a unique id to each enum object, and then allowing switching on the id instead of on the object by writing case FOO.id:.

This breaks the field/getter symmetry, so perhaps we can also allow:

const get x => <potential instance compile time constant expression>

where the expression must be a compile time constant expression potentially containing this.x references to const fields (just as potential const expressions in constructors can refer to const constructor parameters).

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).type-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