Mate Varga
Mate Varga

Reputation: 3416

Is it possible to create Dart class extensions that implement or override inherited methods?

I'd like to use code generators that create extensions for classes that should implement some boilerplate methods, but apparently I cannot :)

Sample code:

abstract class Base {
   foo(int param) { print("Base::foo $param"); }
}

class Derived extends Base {
  
}

extension DerivedWithFoo on Derived {
  foo(int param) { print("Derived::foo $param");}
}

void main() {
 final d = Derived();
 d.foo(5); 
}

Output:

Base::foo 5

It looks like that extension method calls are somehow early bound?

Thanks.

Upvotes: 8

Views: 3837

Answers (1)

Adriano Moreira
Adriano Moreira

Reputation: 195

You can't do this with an extension.

You can try using a mixin instead, like so:

abstract class Base {
  foo(int param) { print("Base::foo $param"); }
}

mixin MyMixin {
  foo(int param) { print("Mixin::foo $param");}
}

class Derived extends Base with MyMixin {
}

void main() {
  final d = Derived();
  d.foo(5);
}

Output:
Mixin::foo 5

Upvotes: 4

Related Questions