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 todynamic get getSound => "Woof"
anddynamic get getSound;
inAnimal
. 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.