Home > Back-end >  functioning of covariant in flutter
functioning of covariant in flutter

Time:02-24

I was going through dart documentation and there I came across this code and this term covariant. I went through some documentation but I didn't get what is its function there. A detailed explained answer is always appreciated.

class Animal {
  void chase(Animal x) { ... }
}

class Mouse extends Animal { ... }

class Cat extends Animal {
  @override
  void chase(covariant Mouse x) { ... }
}

CodePudding user response:

Just try to remove the key word covariant and it will become self explanatory.

You will receive a compiler error that you are overiding a method with mismatch parameter type Expected: Animal, Actual: Mouse

However, Mouse is a subtype of Animal, so if you want to allow this case without error, add the covariant keyword

CodePudding user response:

By using the covariant keyword, you disable the type-check and take responsibility for ensuring that you do not violate the contract in practice.

As you can see in the example, if you are overriding a method, its params should also be the same. But if you are using covariant, it will allow you to use Mouse instead of Animal.

  • Related