Skip to content

check null value of property nested should be cast not nullable #4075

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
bigboss27051 opened this issue Sep 3, 2024 · 2 comments
Closed
Labels
request Requests to resolve a particular developer problem state-duplicate This issue or pull request already exists

Comments

@bigboss27051
Copy link

when I check null property in object in if scope I using that property in if scope null cast type to not nullable

if(object.firstname != null) {
String firstname = object.firstname;
}

this code error because object.firstname can nullable
@bigboss27051 bigboss27051 added the request Requests to resolve a particular developer problem label Sep 3, 2024
@bigboss27051 bigboss27051 changed the title check null nested null cast not nullable check null value of property nested should be cast not nullable Sep 3, 2024
@mateusfccp
Copy link
Contributor

mateusfccp commented Sep 3, 2024

Fields are not promotable1, for technical reasons.2

There's a label with many issues regarding this limitation, called field-promotion.

Currently, the two workarounds you have for this are:

final firstname = object.firstname; // Assignining to a local so it can be promoted

if (firstname != null) {
  // firstname is promoted here to non-nullable
}
if (object.firstname case final firstname?) {
  // firstname is introduced here as a non-nullable local
}

Footnotes

  1. Private fields are promotable in some cases. See this issue.

  2. As far as I know, the main reason is because of field-getter symmetry.

@lrhn
Copy link
Member

lrhn commented Sep 4, 2024

Agree, this is the intended behavior, and while it's a known annoyance, there is no safe way to actually promote public non-local variables without constraining the author from making changes in the future.
For this to be allowed to work, the author of the class would have to have a way to opt in to promotion, like the stable getters (#1518) proposal.

@lrhn lrhn closed this as completed Sep 4, 2024
@lrhn lrhn added the state-duplicate This issue or pull request already exists label Sep 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
request Requests to resolve a particular developer problem state-duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

3 participants