Reputation: 11
Class1 has a property List<ClassA> xyz = [];
. ClassA has a number of properties and methods. ClassB extends ClassA adding additional properties and methods. Is there a way for me to create Class2 extending Class1 but change the TYPE of xyz to List<ClassB>
? If that is confusing hopefully code below will give an example of what I'm trying to accomplish. Basically the same as overriding a method but overriding a property.
class Game {
int points;
String opponent;
int opponentPoints;
}
class FootballGame extends Game {
int touchdowns;
int opponentstouchdowns;
}
class BaseballGame extends Game {
int homeruns;
int opponentsHomeruns;
}
class Team {
String name;
List<Game> games;
double winningPercentage() {
int wins = 0;
for(var game in games){
wins += (game.points > game.opponentPoints) ? 1 : 0;
}
return wins / games.length;
}
}
class FootballTeam extends Team {
// How do I change the TYPE of the games property to <FootballGame>
}
Upvotes: 1
Views: 1746
Reputation: 90175
You could use the covariant
keyword in this case:
class FootballTeam extends Team {
@override
covariant List<FootballGame> games;
}
However, be aware that doing so is potentially unsafe; the reason why you need the covariant
keyword is to suppress the type error that arises because the override can violate the contract of the base class: the base class advertises that games
can be assigned a List<Game>
, but such an assignment would be invalid for the derived class. By using the covariant
keyword, you disable the type-check and take responsibility for ensuring that you do not violate the contract in practice.
Note that if the games
member were final
(or were only a getter), then the override (which uses a more specific type) would be safe and wouldn't need to use covariant
.
I had forgotten that I had written this answer when writing a more detailed answer for a similar question.
Upvotes: 7