dev_mush dev_mush - 4 months ago 33
Dart Question

declaring a method as optional in dart abstract class

As far as I've understood in Dart is possible to use abstract classes to declare "interfaces" or "protocols" (if you come from objective-c).
Anyway I'm having trouble in finding a way to declare an optional method in the abstract class/interface.

If I declare a method in the abstract class A, and let the concrete class B implement A, I get a warning in the compiler.
I'd like to be able to declare a method as optional or at least to provide a default implementation without needing to "re-declare" it in a class that implements my interface.

abstract class A{
void abstractMethod();
}

class B implements A{
//not implementing abstract method here gives a warning
}

Answer

That's not how interfaces work. If your class states to implement an interface, than this is what it has to do.

You can split the interface

abstract class A {
   void abstractMethod();
}

abstract class A1 extends A {
   void abstractMethod();
   void optionalMethod();
}


class B implements A {
 //not implementing abstract method here gives a warning
}

only when it states to implement A1 it has to implement optionalMethod.

Alternatively you can extend the abstract class

abstract class A{
   void abstractMethod();
   void optionalMethod(){};
}

class B extends A {
 //not implementing abstract method here gives a warning
}

then only abstractMethod needs to be overridden because A doesn't provide an implementation.