Skip to content

extension OrDefault<T> on T does not work #15

@gaddlord

Description

@gaddlord

As suggested at https://github.com/vandadnp/flutter-tips-and-tricks/blob/main/tipsandtricks/default-value-for-optionals-in-dart/default-value-for-optionals-in-dart.md

I declared:

extension OrDefault<T> on T {
  T get orDefault {
    final value = this;
    if (value == null) {
      return {
        int: 0,
        String: '',
        double: 0.0,
        num: 0,
        bool: false,
        Map: {},
        List: [],
        Set: {},
      }[T] as T;
    } else {
      return value;
    }
  }
}

  test('Test ObjectExtension.orDefault()', () async {
    const int? nullInt = null;
    expect(nullInt.orDefault, 0); // fails since T is int? and returns null instead of 0.
  });

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