5

I have many objects of the same base type. I want to build a generic function to create them. Code sample :

class Grid extends Display { ....
class Start extends Display { ....

class MainClass {
  Grid grid;
  Start start;
  ....
}

in a MainClass method, instead of this :

start = new Start();
start.load(PATH);

grid = new Grid();
grid.load(PATH);

.... 

I would like to do something like this :

void _newDisplay(dynamicType, Display display) {
  display = new dynamicType();
  display.load(PATH);        
}

_newDisplay(Start, start);
_newDisplay(Grid, grid);

....

I read http://www.dartlang.org/articles/optional-types/ but did not find exactly what I wanted.

I also found Instantiate a class from a string but there is a comment saying : "Note: this might not work when compiled to JavaScript. The dart2js compiler doesn't yet fully support mirrors.". Is this "mirror" solution the only one available to make dynamic instantiation ?

Community
  • 1
  • 1
Eric Lavoie
  • 5,121
  • 3
  • 32
  • 49
  • re: mirrors and dart2js. It is our intention to support mirrors with dart2js, and we're working on it, but it's not 100% yet. Stay tuned! – Seth Ladd May 11 '13 at 04:52

1 Answers1

6

Dart doesn't support a direct way to do this. Usually we work around this by providing a closure that instantiates the type for us:

void _newDisplay(dynamicType, Display display) {
  display = dynamicType();
  display.load(PATH);        
}

_newDisplay(() => Start(), start);
_newDisplay(() => Grid(), grid);

Also see What are some good workarounds for dart's lack of static typing semantics?

Florian Loitsch
  • 7,698
  • 25
  • 30