且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

飞镖比较运算符

更新时间:2022-10-19 10:08:14

我不这么认为。 ,但您可以基于 Comparable 实现使用简单的混合函数来实现运算符:

  mixin Compare< T>在可比较的< T>上{
bool运算符< =(Tother)=> this.compareTo(other)< = 0;

布尔运算符> =(Tother)=> this.compareTo(other)> = 0;

个布尔运算符<(Tother)=> this.compareTo(other)< 0;

布尔运算符>(Tother)=> this.compareTo(other)> 0;

布尔运算符==(other)=>其他是T&& this.compareTo(other)== 0;
}

示例用法:



类Vec。 {
最终双倍x;
最终双倍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));
}


I work on a class for measurements, so I would like to provide a nice API to compare two measurements.

In order to work with ordering in collection I implemented Comparator. For a nice API I implemented as well comparing operators <, <=, =>, >, ==.

So my class has the following methods:

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);

It feels like I had to add way too much boilerplate code. Does Dart provide any mixing for getting all that implementation based on a subset of operators?

I don't think so... but you can use a simple mixin for implementing operators based on the Comparable implementation:

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;
}

Example usage:

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));
}