I'm looking to write a function in a Dart superclass that takes different actions depending on which subclass is actually using it. Something like this:
class Foo {
Foo getAnother(Foo foo) {
var fooType = //some code here to extract fooType from foo;
switch (fooType) {
case //something about bar here:
return new Bar();
case //something about baz here:
return new Baz();
}
}
}
class Bar extends Foo {}
class Baz extends Foo {}
where the idea is that I have some object and want to get a new object of the same (sub)class.
The main question is what type should fooType
be? My first thought was Symbol, which leads to easy case statements like case #Bar:
, but I don't know how I would populate fooType
with a Symbol. The only options I can think of are to do something like Symbol fooType = new Symbol(foo.runtimeType.toString());
but my understanding is that runtimeType.toString()
won't work when converted to javascript. You could get around that by using Mirrors, but this is meant to be a lightweight library, so those aren't on the table. Object.runtimeType
returns something of the Type
class, but I have no idea how to create instances of Type
I could use for the case statements. Maybe I'm missing some other piece of the Dart library that is better suited for this?