Reputation: 3750
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
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