SoulCRYSIS
SoulCRYSIS

Reputation: 629

How to automatic declare operator for class?

For example, I want operator+ to plus every field in class

class Test {
  final int var1;
  final int var2;
  final int var3;
  final int var4;

  Test(this.var1, this.var2, this.var3, this.var4);

  Test operator +(Test other) {
    return Test(
      var1 + other.var1,
      var2 + other.var2,
      var3 + other.var3,
      var4 + other.var4,
    );
  }
}

This very cumbersum and duplicated, especially when I have many fields (let say 100), I just want to add every field.

Is there other way to do this faster? Why it didn't have default operator+?

Upvotes: 3

Views: 83

Answers (2)

SoulCRYSIS
SoulCRYSIS

Reputation: 629

I found a solution to work around this.

By convert it to a map using json_serializable and iterate through the map

@JsonSerializable()
class Test {
  final int var1;
  final int var2;
  final int var3;
  final int var4;

  Test(this.var1, this.var2, this.var3, this.var4);

  factory Test.fromJson(Map<String, dynamic> json) => _$TestFromJson(json);
  Map<String, dynamic> toJson() => _$TestToJson(this);

  Test operator +(Test other) {
    final thisJson = toJson();
    final otherJson = other.toJson();
    final Map<String, dynamic> result = {};
    for (var key in thisJson.key) {
      result[key] = thisJson[key] + otherJson[key];
    }
    return Test.fromJson(result);
  }
}

*Note: this code is inefficient in term of performance (it has to encode and decode JSON), so don't do this if you call this operator a lot.

Upvotes: 0

GiuseppeFn
GiuseppeFn

Reputation: 405

This isn't possible, as dart isn't a reflective language, so its code can't inspect itself.

To give you a clearer idea, here an example of what you could use, but in Java, you could probably achieve what you're trying to do with this language feature.

So, long story short, you can't do this in dart, at the moment.

Upvotes: 1

Related Questions