Skip to content

Cannot use record as default value for optional parameter of class constructor #53321

Closed
@chykon

Description

@chykon

Cannot use record as default value for optional parameter of class constructor.

Static analysis shows error non_constant_default_value. When I try to start, I get several errors:

  • Error: Not a constant expression.
  • Error: Constant evaluation error:

Example code (DartPad):

abstract class AnimalNames {
   static const dogName = (buddy: 'Buddy');
}

class Dog {
   Dog({this.name = AnimalNames.dogName.buddy});

   final String name;
}

void main() {}

Functionally similar working code that doesn't use record (DartPad):

abstract class AnimalNames {
   static const dogNameBuddy = 'Buddy';
}

class Dog {
   Dog({this.name = AnimalNames.dogNameBuddy});

   final String name;
}

void main() {}

Dart version used: DartPad stable channel (Based on Flutter 3.13.0 Dart SDK 3.1.0)

Activity

lrhn

lrhn commented on Aug 23, 2023

@lrhn
Member

This is working as intended. The expression AnimalNames.dogName.buddy is not a constant expression, because it calls a getter.

That getter happens to be the getter of a record field of a constant record. We could safely allow that, because we know the getter is definitely side-effect free and we can evaluate it at compile-time. But we currently do not allow it.

There is already a language request for that: dart-lang/language#3004
so closing this and deferring to the language repo issue.

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

    closed-duplicateClosed in favor of an existing report

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @lrhn@chykon

        Issue actions

          Cannot use `record` as default value for optional parameter of class constructor · Issue #53321 · dart-lang/sdk