Home > Net >  How to access a method from the extended abstract class when using it as a type constraint in a meth
How to access a method from the extended abstract class when using it as a type constraint in a meth

Time:07-12

Say I have this abstract class

abstract class Animal{
  static dynamic getSound(){}
}

And this other class extending it

class Dog extends Animal{
  static dynamic getSound(){
    return "Woof";
  }
}

And I want to use a method to access the static method of those classes by sending the type of Animal I want, like this:

dynamic getAnimalSound<T extends Animal>(){
  return T.getSound();  
}

Except this doesn't work because it isn't assumed that T extends Animal so there I can't access it.

What can I do make this getAnimalSound method working?

CodePudding user response:

What I would do in your place is to use overriding. However, it also only works on non static methods. (untested but should work)

abstract class Animal{
  dynamic getSound();
}

class Dog extends Animal{
  @override
  dynamic getSound(){
    return "Woof";
  }
}

dynamic getAnimalSound(Animal animal){
  return animal.getSound();  
}

Some other tips: (there is nothing wrong with your code though!)

  • Dart has special syntax for getters and setters, so you could rewrite your getSound() method to dynamic get getSound => "Woof" and dynamic get getSound; in Animal. Which is a bit cleaner imo.
  • If your sounds are just strings, dont use dynamic, use String as a return type... It will have better type checking.
  • Related