Dart: different static methods for each child class Dart: different static methods for each child class dart dart

Dart: different static methods for each child class


If the problem is that the generic class depends on the zero value, the immediate solution should be to pass the zero value to the generic class instance when it is created (just as you pass the type parameter).

That is:

class GenericClass<T extends ParentClass> {  final T zero;  GenericClass(this.zero);}

and

.. new GenericClass<ChildClass>(ChildClass.zero);

I recommend making the 'zero' field a const if possible.

This is likely to be the best/only solution that allows your generic class to have a zero object available, short of using mirrors (which would be overkill).

You cannot access static members on a type parameter, as you know. Static members are resolved at compile time, so the lookup can't vary between instances depending on the type parameter. That also shoots down most other attempts to use a static or const field directly.

You can make an instance method on each of your classes that return a zero instance (you can make it const if possible, or store it in a private static field to avoid creating a new one each time). That requires you to have an instance before being able to get the zero instance, and not having an instance is likely to be the reason for needing a zero instance, so that probably won't fly either.


Static functions are not part of a class' interface therefore <T extends ParentClass> doesn't help.Static function can only be accessed by MyClassName.myFunctionName().
I don't know of a solution for your requirement.

What I did in a similar situation was to declare a static field that holds the value and a non-static getter that returns the static value.
But this way you still have to have an instance to get access to the value (or access it with the literal class name as prefix).