Search code examples
dartoverridingvoidreturn-type

Method Overriding in Dart when the Return Type is "void"


I anticipated a compile-time error when overriding a method in Dart without the correct (to my knowledge so far) return type. However, things seem to be different when the return type of the method is void:

abstract class AbstractClass {
  void methodDoesNotReallyReturnVoid();
}

class ConcreteClass extends AbstractClass {
  // NO ERROR here!
  @override
  int methodDoesNotReallyReturnVoid() => 12;
}

void main() {
  print(ConcreteClass().methodDoesNotReallyReturnVoid()); // hm...?
}

The code above compiles without complaints and prints the integer as expected though I did not properly override that method like, for example, in Java.

May I know what is distinct about "void" here?


Solution

  • @Ardent Coder's answer cites specific details, but a short version is:

    Can the int methodDoesNotReallyReturnVoid() override satisfy the contract of the base void methodDoesNotReallyReturnVoid() method? Yes, because the returned value can simply be ignored.