Thorsten
Thorsten

Reputation: 33

How can I overload the + operator on String in dart?

I tried to overload the + operator on the String class to be able to add an int to a String. 'A'+1 should produce 'B'. But it does not work in dartpad. How can I make it work?

extension StringExt on String {
  String operator +(int i) {
    return String.fromCharCode(this.codeUnitAt(0) + i);
  }
}

void main() {
  String s = 'A';
  print('A' + 1);
}

Upvotes: 2

Views: 294

Answers (1)

lrn
lrn

Reputation: 71763

You cannot add an extension method named + on String since String already has an operator named +.

Dart can only have one member with each name on each class (no member overloading), and extension members have lower priority than existing instance members.

You can actually call the extension +, but you need to explicitly invoke the extension to avoid String.operator+ taking precedence:

 print(StringExt('A') + 1);

That removes most of the advantage of having a short operator.

As mentioned, you can use a different name:

extension CharCodeInc on String {
  String operator /(int i) => String.fromCharCode(codeUnitAt(0) + i);
}
...
  print("A"/2); // prints "C"

Too bad all the good names are taken (at least + and * on strings).

Upvotes: 2

Related Questions