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

Answer to null check question in painter's code #55

Open
feinstein opened this issue Dec 15, 2023 · 2 comments
Open

Answer to null check question in painter's code #55

feinstein opened this issue Dec 15, 2023 · 2 comments
Labels
good first issue Good for newcomers

Comments

@feinstein
Copy link

The painter's code have this question:

  if (image != null && imageFit != null) {
    // TODO: why the ! are needed here, as check against null been performed?

The answer is, the compiler can't know if a class' filed is always null or not, because this field could be a getter that returns null sometimes and returns a value other times. You need to use the ! operator or you can copy that field to a local variable and check that variable, then the compiler knows it's not null at all.

Example:

  final image = this.image;
  if (image != null && imageFit != null) {
    // compiler knows image is not null and you don't need to use the ! operator.
@vintage vintage added the good first issue Good for newcomers label Dec 22, 2023
@vintage
Copy link
Owner

vintage commented Dec 22, 2023

Thanks! Labeling it as good first issue. If you or anyone else want to make the PR to resolve that, I'm happy to merge!

@feinstein
Copy link
Author

No need to fix, it's just a preference of style. Copying to a local variable is safer, but just for extreme cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

2 participants