[异常] is not a subtype of type ‘Comparable‘ in type cast

is not a subtype of type 'Comparable<dynamic>' in type cast 这个错一般是怎么导致的呢,检查你的代码是不是用了 List.sort() 对集合排序。

如果是基本数据类型的集合,比如 List 使用 sort() 排序是可以的,但如果是一个自定义对象,而对象又没实现 Comparable 接口,就会报以上错误。

如何实现呢,这里我用一个对象举例,你们可以参考修改自己的对象

  class Person implements Comparable<Person> {
    final String name;
    final int age;
    final bool male;
    final double score;

    Person(this.name, this.age, this.male, this.score);

    @override
    int compareTo(Person other) {
      // 首先根据 name 属性进行比较
      int nameComparison = name.compareTo(other.name);
      if (nameComparison != 0) {
        return nameComparison;
      }

      // 如果 name 相同,根据 age 属性进行比较
      int ageComparison = age.compareTo(other.age);
      if (ageComparison != 0) {
        return ageComparison;
      }

      // 如果 name 和 age 都相同,根据 male 属性进行比较
      if (male != other.male) {
        return male ? 1 : -1;
      }

      // 如果 name、age 和 male 都相同,根据 score 属性进行比较
      return score.compareTo(other.score);
    }
  }

OK,希望以上能帮到你。

本文由老郭种树原创,转载请注明:https://guozh.net/is-not-a-subtype-of-type-comparable-in-type-cast/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注