【问题标题】:Dart comparison operatorsDart 比较运算符
【发布时间】:2019-08-13 07:41:06
【问题描述】:

我在做一个测量类,所以我想提供一个很好的 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 是否提供任何混合以基于运算符子集获得所有实现?

【问题讨论】:

    标签: dart


    【解决方案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));
    }
    

    【讨论】:

    • 唯一缺少的部分是,如果你覆盖equals,你也应该覆盖hashCode
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多