0

Problem

I would like to create a function (brilliantFunction) for a set of classes (SubClass1, SubClass2, SubClass3) which all decent from one super class (SuperClass).

  • SuperClass has the static function doSth()
  • Each sub class overrides this function differently
  • brilliantFunction uses this static function from one of the sub classes through generics

My idea:

abstract class SuperClass {
    static void doSth();
}

class SubClass1 extends SuperClass {
    @override
    static void doSth() {
        ... // does something
    }
}

... // somewhat the same for SubClass2+3

and the part that does not work:

void brilliantFunction<T extends SuperClass> () {
    T.doSth() // <-- This does not work :(
}

Seems like I am not the only one trying to do it. And this person is asking sth differently. So apparently it actually should work just as I thought?

1 Answers1

0

You try to override a static method. See the accepted answer here, static methods are not inherited in Dart.

When you want to call the doSth function you need an object and not a type. So you need to pass an object to brilliantFunction so that you can call the method doSth on it.

Check the following code, you can copy & paste into DartPad if you like. The printed messages show which function is called, also look at the super.doSth() call in SubClass3:

void main() {
  final sub1 = SubClass1();
  final sub2 = SubClass2();
  final sub3 = SubClass3();
  
  brilliantFunction(sub1);
  brilliantFunction(sub2);
  brilliantFunction(sub3);
}

void brilliantFunction<T extends SuperClass> (T value) {
    value.doSth();
}

abstract class SuperClass {
    void doSth() {
      print('SuperClass.doSth');
    }
}

class SubClass1 extends SuperClass {
    @override
    void doSth()  {
      print('SubClass1.soSth');
    }
}

class SubClass2 extends SuperClass {
    @override
    void doSth()  {
      print('SubClass2.soSth');
    }
}

class SubClass3 extends SuperClass {
    @override
    void doSth()  {
      super.doSth();
      print('SubClass3.soSth');
    }
}

If you need only one instance from these objects in your application, I suggest some kind of singleton pattern.

Peter Koltai
  • 8,296
  • 2
  • 10
  • 20
  • Although there is no instance I could pass to the function (that's why it's static) it makes sense why it does not work. Thanks a lot! – MisterMirko Feb 28 '23 at 10:19
  • You are welcome. You can easily make a singleton class that will create automatically one instance first time you access it in your code. Later you can use this one instance. This pattern is widely used in Flutter in official plugins like Firebase. – Peter Koltai Feb 28 '23 at 10:35