Не удается расширить Num с помощью пользовательской перегрузки оператора для достижения коммутативного правила. - PullRequest
0 голосов
/ 11 января 2020

У меня есть класс Amount, в который я добавил оператор умножения, который отлично работает (amount * 3). Чтобы добиться поведения (3* amount), я добавил метод расширения к типу num.

/// file path: src/domain/entities/amount/amount.dart
class Amount {
  final double amount;
  final String unit;
  Amount({
    @required this.amount,
    @required String unit,
  });
...
 Amount operator *(num multiplier) => copyWith(amount: amount * multiplier);
...
}

extension NumAmountExtension<T extends num> on T {
  Amount operator *(Amount amount) => amount * this;
  Amount multiply(Amount amount) => amount * this;
}

К сожалению, это не сработало.

/// file path: test/domain/entities/amount_tests.dart
final amount = Amount(amount: 3, unit: 'kg')
final newAmount = amount * 3;
final newerAmount = 3.multiply(amount) // this works fine
final otherNewAmount = 3 * amount //error: The argument type 'Amount' can't be assigned to the parameter type 'num'. (argument_type_not_assignable at [core] test/domain/entities/amount_tests.dart:83)

Я делаю не понимаю, почему расширение multiple работает, а operator * - нет. Насколько я понимаю, метод расширения понимает, что это возможно.

...