Skip to content

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

@gaddlord

Description

@gaddlord

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions