About Challenge 2 solution code in Chapter 6 Mixins

The solution code try to implements Comparable<Platypus>

My code don’t have the <Platypus> type declaration, see below:

class Platypus extends Animal with EggLayer implements Comparable {
  @override
  void eat() {
    print('Munch munch');
  }

  @override
  void move() {
    print('Glide glide');
  }

  double weight = 3.14;

  @override
  int compareTo(other) {
    if (weight > other.weight) {
      return 1;
    } else if (weight < other.weight) {
      return -1;
    }
    return 0;
  }
}

What is the difference between adding or not adding <Platypus>? Is it recommended? But overall I’m not quite understand the meaning of adding a type behind class name.

You’re solution is fine, especially at this point in the book. In chapter 8 you’ll learn about generics. Generics just refers to certain classes being able handle any generic type. For example, List can handle any type. You can have a list of String, a list of int, a list of Object, etc. The notation for telling Dart the type of the generic class is to use angle brackets:

  • List<String>
  • List<int>
  • List<Object>

If you just use the class name List without specifying the generic type, then Dart doesn’t know what it is and will just default to List<dynamic>. Recall that dynamic means that no type is given. This breaks type safety, so it’s generally good to specify the type. When you have type safety, Dart can tell you about errors at compile time. Without type safety you don’t find out about the errors until runtime.

Comparable is also generic. You can compare strings or integers or anything that implements the Comparable interface (that is, it includes a compareTo method). However, if you just use Comparable without specifying the type, Dart doesn’t know what it’s comparing. You can see this if you hover over other in int compareTo(other) in your code example. (Or click other if you are using DartPad.) Dart will infer the type to be dynamic. Using Comparable<Platypus>, on the other hand, tells Dart that you are comparing Platypus objects. Hovering over other now shows that it is of type Platypus.

2 Likes

Hi @ellery,

Thank you for reaching out to us with your question. We hope that the response provided was helpful in addressing your concerns.

If you have any further questions or need additional assistance, please don’t hesitate to ask. Our community is here to support you!

Thanks @suragch