Home > database >  How to automatic declare operator for class?
How to automatic declare operator for class?

Time:06-05

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 ?

CodePudding user response:

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.

  • Related