0

I have a few classes that inherit from a base class. The inherited classes have fields that are not relevant for the other classes.

abstract class Game {}

class SingleplayerGame extends Game {
  int level;
}

class MultiplayerGame extends Game {
  int numberOfRounds;
}

I thought I could do something like this:

Game game;
String title = game is MultiplayerGame 
  ? "Rounds: ${game.numberOfRounds.toString()}"
  : game is SingleplayerGame
    ? "Level: ${game.level.toString()}" : "";

I'm getting the error The getter 'numberOfRounds' isn't defined for the type 'Game'.

NicklasF
  • 863
  • 3
  • 10
  • 26
  • (game as MultiplayerGame).numberOfRounds, but make sure you checked the type before you do so – Olga Jan 25 '23 at 16:24
  • Your code should work fine if `game` is a local variable. [Only local variables can be automatically type-promoted](https://stackoverflow.com/q/56764592/). – jamesdlin Jan 25 '23 at 16:31

0 Answers0