Switching on class type in Dart

2020-03-01 07:18发布

问题:

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?

回答1:

You can use the runtimeType in switch :

class Foo {
  Foo getAnother(Foo foo) {
    switch (foo.runtimeType) {
      case Bar:
        return new Bar();
      case Baz:
        return new Baz();
    }
    return null;
  }
}

In the case statements the class name is use directly (aka. class literal). This gives a Type object corresponding to the class mentionned. Thus foo.runtimeType can be compared with the specified type.

Note that you can not use generics for now in class literals. Thus case List<int>: is not allowed.



标签: dart