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

Null-Aware Infix Operators in Dart - likely unneeded code on line "return shadow + (other ?? 0) as T" #17

Open
gaddlord opened this issue Aug 20, 2022 · 1 comment

Comments

@gaddlord
Copy link

RE: https://github.com/vandadnp/flutter-tips-and-tricks/blob/main/tipsandtricks/null-aware-infix-operators-in-dart/null-aware-infix-operators-in-dart.md

Having:

T? operator +(final T? other) {
  final shadow = this;
  if (shadow != null) {
    return shadow + (other ?? 0) as T;
  } else {
    return null;
  }
}

and the test:

test('Test null + operator', () {
    int? var1;
    var1++;
    var1 += 1;
    var1 = var1 + 1;
    var1 = 2;
    var1++;
    var1 += 1;
    var1 = var1 + 1;
    expect(var1, 5);
}

The test runs successfully but with code coverage we can see that the line

return shadow + (other ?? 0) as T;

never gets called which leads me to the speculation that shadow always equals to NULL when the extension is called and the extension is not "attached" if T is not null.

@misterfourtytwo
Copy link

@gaddlord as far as i understand, in your example precedence gets default int + operator.
int and double are not strictly classes, because they are implemented on the platform-specific basis, thus it can be considered a corner case.
well, you still can get expected behavior with explicit spec, like on screenshot
image

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

No branches or pull requests

2 participants