6

Can you can make extension methods in dart? like you can in C# e.g.:

void swap(this CssClassSet ccs, String oldClass, String newClass)
{
    ccs.remove(oldClass);
    ccs.add(newClass);
}

is this sort of thing possible with Dart? I would like to extend CssClassSet to have a swap(String oldClass, String newClass) method.

Daniel Robinson
  • 13,806
  • 18
  • 64
  • 112

3 Answers3

7

6 years later and extension functions are finally on the horizon: https://github.com/dart-lang/language/issues/41#issuecomment-539251446

They will be included in dart 2.6

lhk
  • 27,458
  • 30
  • 122
  • 201
3

Not yet. See issue 9991 - scoped object extensions.

Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • `Rejected` in this case, it would be unwise. This reduces the appeal. `Accepted` in this case does not mean anything. Read Gilad Bracha comments at this issue [Add C#-style extension methods](https://code.google.com/p/dart/issues/detail?id=13). – mezoni Jul 26 '13 at 18:17
  • 1
    There's been an update and the discussion is now moved [here](https://github.com/dart-lang/language/issues/177) – kosiara - Bartosz Kosarzycki Mar 25 '19 at 17:02
3

Yes, this was introduced in Dart 2.6.

The syntax is the following:

extension YourExtension on YourClass {
  void yourFunction() {
    this.anyMember(); // You can access `anyMember` of `YourClass` using `this`.
    anyMember(); // You can access `anyMember` of `YourClass` without `this`.
  }
}

void main() {
  YourClass yourVariable;

  yourVariable.yourFunction(); // valid
}

You can also extend types like int:

void main() {
  5.fancyPrint();
  3.minusThree; // returns 0
}

extension FancyInt on int {
  void fancyPrint() => print('The magic number is $this.');

  int get minusThree => this - 3;
}

You can learn more here.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402