Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching on class type in Dart

Tags:

dart

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?

like image 533
Michael Fenwick Avatar asked Jan 22 '15 08:01

Michael Fenwick


People also ask

What is switch in Dart?

Dart Switch case statement is used to avoid the long chain of the if-else statement. It is the simplified form of nested if-else statement. The value of the variable compares with the multiple cases, and if a match is found, then it executes a block of statement associated with that particular case.

How do you check data type in Dart?

Dart objects have runtimeType property which returns Type . To check whether the object has a certain type, use == operator. Unlike is , it will only return true if compared to an exectly same type, which means comparing it with its super class will return false .


Video Answer


1 Answers

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 used directly (AKA class literal). This gives a Type object corresponding to the class mentioned. 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.

like image 104
Alexandre Ardhuin Avatar answered Oct 13 '22 07:10

Alexandre Ardhuin