Enabling class type in Dart

I want to write a function in a Dart superclass that takes different actions depending on which subclass actually uses it. Something like that:

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 kind of object and you 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 statements with light arguments like case #Bar: but I don’t know how I would fill fooType symbol. The only options I can think of is to do something like Symbol fooType = new Symbol(foo.runtimeType.toString()); but I understand that runtimeType.toString() will not work when converting to javascript. You can get around this using Mirrors, but that means it is a small library, so they are not on the table. Object.runtimeType returns something from the Type class, but I have no idea how to create Type instances that I could use for case statements. Maybe I am missing some other part of the Dart library that is better suited for this?

+6
source share
1 answer

You can use 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 case the class name is used directly (aka. Class literal). This gives a Type object corresponding to the specified class. Thus, foo.runtimeType can be compared with the specified type.

Note that you cannot use generics at this time in class literals. Thus, case List<int>: not allowed.

+7
source

Source: https://habr.com/ru/post/981386/


All Articles