Skip to content

Record fields can't be used as const? #51895

Closed
@mdebbar

Description

@mdebbar

In the following code snippet, info.age is a const value (the entire info record is const). But the analyzer isn't happy with it.

const info = (name: 'John', age: 20);

String getNameByAge(int age) {
  switch (age) {
    case info.age: return info.name;
    default: 'unkown';
  }
}

I get the following error about case info.age:

The expression of a constant pattern must be a valid constant.

Try making the expression a valid constant.

Is this working as intended or a bug?

Activity

eernstg

eernstg commented on Mar 30, 2023

@eernstg
Member

This is working as intended: The only getter which can be invoked as part of constant expression evaluation is length, and that is only allowed when the receiver is an instance of String (that's the actual value of the constant expression, not the static type).

Check out https://github.com/dart-lang/language/issues?q=is%3Aopen+is%3Aissue+label%3Aenhanced-const for issues about generalizations of the constant expression sublanguage in general, and, e.g., dart-lang/language#2219, where several new constant expression forms are proposed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @mdebbar@bwilkerson@eernstg

        Issue actions

          Record fields can't be used as const? · Issue #51895 · dart-lang/sdk