Skip to content

Allow const to be inferred for enum constructors #4494

@eernstg

Description

@eernstg

We currently require every generative constructor in an enum declaration (redirecting or not) to have the modifier const. This is somewhat redundant because it is an error for such constructors to be non-constant. Nevertheless, we have reported a missing const as a compile-time error rather than inferring it, mostly based on the argument that it hurts the readability of the code if a constructor is actually constant even though it does not have this modifier.

A similar argument can be made for an enum constructor which is a redirecting factory.

This issue is a proposal that we should change the rule and make const optional on each enum constructor which is a generative constructor (redirecting or not), or a redirecting factory. We would then infer the const-ness in the situation where it isn't specified explicitly.

Non-redirecting factory constructors can not (currently) be constant, so they are not included.

A constructor whose const modifier has been inferred is a constant constructor, exactly like a constructor where const is specified explicitly, and the semantics and error handling proceeds accordingly.

This proposal can be seen as one of several possible steps where properties which are required can be inferred when they are not specified. Inference of required on formal parameters is another example. Inference of the return type void for a setter is yet another which is already part of the language.

Note that it is unlikely to be useful to infer const on constructors of classes, mixin classes, or extension types: It would (probably) have to be done based on a check that any given constructor as written would not be an error if const were added. This involves checking properties of the constructor itself, plus checking properties of the class (in particular: all instance variables must be final, and their initializing expressions, if any, must be constant expressions).

However, it is a breaking change to remove const-ness from a constructor, which would happen silently if any changes were made to a constructor such that it is no longer inferred to be constant. This could break code in client libraries, and it might not be easy to eliminate such errors.

This means that enum declarations are a special case, hence the limitation of this proposal that that kind of declaration.

Metadata

Metadata

Assignees

No one assigned

    Labels

    small-featureA small feature which is relatively cheap to implement.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions