What is "covariant" in Dart?

Tue, Dec 20, 2022

Read in 2 minutes

In this post we take a look at "covariant" keyword with some example codes.

In Dart, covariant is a keyword that is used to modify the behavior of method parameters in class hierarchies.

When a method is declared with a parameter that has a type that is a superclass of the actual type of the parameter, the method is said to be “contravariant” with respect to that parameter. This means that a subclass can override the method and provide a more specific type for the parameter than the superclass, without causing any problems for the calling code.

However, there are cases where a method parameter should be allowed to have a more specific type in the subclass, even if the parameter has a less specific type in the superclass. This is where the covariant keyword comes into play.

When you mark a method parameter with the covariant keyword, you are telling the Dart compiler that it is okay for the parameter to have a more specific type in a subclass. This is known as making the parameter “covariant” with respect to the method.

Here is an example to illustrate the use of covariant:

class Animal {
  void speak(covariant String message) {
    print('Animal says: $message');
  }
}

class Dog extends Animal {
  void speak(String message) {
    print('Dog says: $message');
  }
}

void main() {
  Animal myDog = new Dog();
  myDog.speak('Woof!'); // Output: Dog says: Woof!
}

In this example, the Animal class has a speak method that takes a String parameter. The Dog class overrides this method and also takes a String parameter, but without the covariant keyword.

When we create an instance of Dog and assign it to a variable of type Animal, we can call the speak method with a String parameter that is more specific than the parameter declared in the Animal class. This is possible because we marked the parameter with the covariant keyword in the Animal class.

Without the covariant keyword, this code would not compile because the parameter types in the subclass must be the same as or less specific than the parameter types in the superclass.

In summary, the covariant keyword in Dart is used to modify the behavior of method parameters in class hierarchies. It allows a subclass to provide a more specific type for a method parameter than the superclass, without causing any problems for the calling code.


Shohruh AK



Category:

Dart

Tags:



See Also

What is "continue" in Dart?
What is "class" in Dart?
What is "case" in Dart?
What is "break" in Dart?
What is "async" in Dart?