飞镖比较运算符

时间:2019-03-22 10:27:10

标签: dart

我正在研究测量类,因此我想提供一个不错的API来比较两个测量。

为了处理集合中的订购,我实施了Comparator。对于一个不错的API,我还实现了比较运算符<<==>>==

所以我的课有以下方法:

bool operator <=(SELF other) => _value <= other._value;

bool operator <(SELF other) => _value < other._value;

bool operator >(SELF other) => _value > other._value;

bool operator >=(SELF other) => _value >= other._value;

@override
bool operator ==(Object other) =>
    identical(this, other) || other is UnitValue && runtimeType == other.runtimeType && _value == other._value;

@override
int get hashCode => _value.hashCode;

int compareTo(SELF other) => _value.compareTo(other._value);

感觉就像我不得不添加太多样板代码。 Dart是否提供任何混合,以便基于一部分运算符获得所有实现?

1 个答案:

答案 0 :(得分:1)

我不这么认为...但是您可以使用一个简单的mixin基于Comparable实现来实现运算符:

mixin Compare<T> on Comparable<T> {
  bool operator <=(T other) => this.compareTo(other) <= 0;

  bool operator >=(T other) => this.compareTo(other) >= 0;

  bool operator <(T other) => this.compareTo(other) < 0;

  bool operator >(T other) => this.compareTo(other) > 0;

  bool operator ==(other) => other is T && this.compareTo(other) == 0;
}

用法示例:

class Vec with Comparable<Vec>, Compare<Vec> {
  final double x;
  final double y;

  Vec(this.x, this.y);

  @override
  int compareTo(Vec other) =>
      (x.abs() + y.abs()).compareTo(other.x.abs() + other.y.abs());
}

main() {
  print(Vec(1, 1) > Vec(0, 0));
  print(Vec(1, 0) > Vec(0, 0));
  print(Vec(0, 0) == Vec(0, 0));
  print(Vec(1, 1) <= Vec(2, 0));
}