Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
chykon opened this issue Aug 23, 2023 · 1 comment
Closed
Labels
closed-duplicate Closed in favor of an existing report

Comments

@chykon
Copy link

chykon commented Aug 23, 2023

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)

@lrhn
Copy link
Member

lrhn commented Aug 23, 2023

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.

@lrhn lrhn closed this as completed Aug 23, 2023
@lrhn lrhn added the closed-duplicate Closed in favor of an existing report label Aug 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-duplicate Closed in favor of an existing report
Projects
None yet
Development

No branches or pull requests

2 participants