Search code examples
dartabstract-class

Dart: How to define an abstract class for Model Objects which has a function that takes it's own type as a parameter


i have the following Problem in Dart:

i want to define an abstract class ModelObjects which has some functions. Among them is the function isSame

abstract class ModelObject{
   bool isSame(ModelObject object);
   ...
}

Now I'm defining the class PlayerModel as follows:

class PlayerModel extends ModelObject{
     bool isSame(PlayerModel player){
       //some code that checks if the objects are the same
     }

which leads dart to give me a compiling error:

PlayerModel.isSame' ('bool Function(PlayerModel)') isn't a valid override of 'ModelObject.isSame' ('bool Function(ModelObject)').dart(invalid_override)

I've managed to sidestep this issue by making ModelObjects a generic

abstract class ModelObject<T>{
    bool isSame(T object);}

But this seems to be more a cheat than a solution.

Now my question is: Is there a more elegant way to solve this problem or are abstract classes simply the wrong approach in this case?


Solution

  • I believe that you can use the covariant keyword:

    class PlayerModel extends ModelObject {
      @override
      bool isSame(covariant PlayerModel player) {
        //some code that checks if the objects are the same
      }