Skip to content
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

Error in modifiying of const list #6341

Open
1 task
sairaorgb opened this issue Jan 18, 2025 · 1 comment
Open
1 task

Error in modifiying of const list #6341

sairaorgb opened this issue Jan 18, 2025 · 1 comment
Labels
from.page-issue Reported in a reader-filed concern

Comments

@sairaorgb
Copy link

Page URL

https://dart.dev/language/variables/

Page source

https://github.com/dart-lang/site-www/tree/main/src/content/language/variables.md

Describe the problem

var foo = const [];
foo = [1, 2, 3]; // Was const []
this was listed in the docs , but this is wrong right . we cant modify foo here

Expected fix

No response

Additional context

No response

I would like to fix this problem.

  • I will try and fix this problem on dart.dev.
@sairaorgb sairaorgb added the from.page-issue Reported in a reader-filed concern label Jan 18, 2025
@thisissandipp
Copy link

We can, actually. The foo variable is declared using var, making it mutable. The value initially assigned to foo is a constant (an empty list) but can be reassigned because the variable itself is not marked as const or final.

Here is an equivalent code for the above example

const arr = [];
var foo = arr;

foo = [1, 2, 3];  // CAN DO THIS!
arr = [3, 4, 5];  // ERROR - CAN NOT DO THIS!

In this case, arr is a constant and cannot be modified, but foo is a regular variable and can be reassigned to a different list without any issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
from.page-issue Reported in a reader-filed concern
Projects
None yet
Development

No branches or pull requests

2 participants