rich.e
rich.e

Reputation: 3750

Is it possible to initialize a generic instance variable in constructor?

I was wondering today if there is any way to ensure a generic instance variable is initialized upon construction in dart. Take the following basic example:

class MovingObject<T> {
  T _value;

  MovingObject() {
    // ???: how to init _value here?
  }
}

In C++, you can do this by specializing the constructor for known types, ex. I could set a float _value to 0 or Vector3 value to [0, 0, 0]. Is this possible in dart?

Upvotes: 1

Views: 385

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658263

One way that comes to my mind is

class MovingObject<T> {
  T _value;

  MovingObject() {
    // ???: how to init _value here?

    switch(T) {
      case int:
        _value = (5 as T);
        break;
      default:
        ClassMirror x = reflectType(T);
        _value = x.newInstance(new Symbol(''), []).reflectee; // '' for default constructor
        break;
    }
  }
}

class SomeType {
}

Upvotes: 2

Related Questions