-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Failed to assign to final instance variable in constructor #427
Comments
This comment was originally written by [email protected] You can put both the assignments into the initializer list, can't you? class Object { final _foo; Slightly suboptimal (I love the shorthand syntax Obj(this._foo) in constructor arguments), but not exactly bad. |
This comment was originally written by [email protected] Apparently I can, yes. It's a shame there's an inconsistency there, but Thanks! |
This comment was originally written by [email protected] Removed Type-Defect label. |
There's no inconsistency. We require final fields to be initialized in the initializer list, so we can ensure they get initialized. We do not allow access to 'this' on the right hand side of assignmenyts in the initializer list, so we don't have dependencies on virtual method calls and uninitialized fields etc. Hence the need to initialize _bar in the initializer list using a parameter rather than _foo. The this.x initializing parameter sugar is for the common case where the only use of the parameter is to initialize a field. The parameter is not in scope in the constructor body or initializer list. In more complex cases, you live without the sugar. |
mainly, this backs off of some readability optimizations around static and top-level fields that were too aggressive. On their own, they were okay, but they collide with the library-cycle issues. Once we can remove that issue, we could consider restoring some of this. In the meantime, simplicity is good. The new operation in the declaration loader is to allow us to see if an initializer has all its dependencies satisfied, but without changing any ordering if they are not. [email protected] Review URL: https://codereview.chromium.org/1636233002 .
This issue was originally filed by [email protected]
I believe this should be legal:
class Object {
Object(this._foo) {
_bar = _foo.bar;
}
final _foo;
final _bar;
}
However I get the error 'cannot assign value to final variable _bar'. I can't put the assignment in the initializer list as the assignment refers to _foo.
As it is, the only solution I've found is to make _bar non-final which is less than ideal.
The text was updated successfully, but these errors were encountered: