Open
Description
Occasionally one needs to work with different types of object in different scenarios, frequently subclasses of the same type. I frequently have functions that I need to return them. My current solution looks like this:
class Foo {
@override
String toString() => "Foo!";
}
class Bar extends Foo {
@override
String toString() => "Bar!";
}
class Baz extends Foo {
@override
String toString() => "Baz!";
}
Foo instantiate(Type type) {
switch(type) {
case Foo: return Foo();
break;
case Bar: return Bar();
break;
case Baz: return Baz();
break;
default: return Foo();
}
}
void main() {
Type foo = Foo; // returned from some indeterminate function
var instance = instantiate(foo);
print(instance); // "Foo!"
}
A more elegant way of doing this, IMO, would be the ability to instantiate a Type with (), or the new keyword. Possibly we could also add a generic parameter for Type? Syntax could look like this:
void main() {
// Foo and Bar from previous code snippet
Type foo = Foo;
var instance = foo(); // type: dynamic
print(instance); // "Foo!"
Type<Foo> typedFoo = Foo;
var typedInstance = new typedFoo(); // type: Foo
print(typedInstance); // "Foo!"
// also valid!
Type<Foo> bar = Bar;
var barInstance = bar(); // type: Foo
print(barInstance); // "Bar!"
}