skip to Main Content

In Dart, I can override the toString method to change the string content returned by an object when it is used as a string.

I need to change the object’s behavior when it is used as a double.

I would like to achieve the same result from this C++ code in Dart:

class Value {
private:
  double value;
  Color color;

public:
  Value(double value, Color color) : value(value), color(color) {}
  operator double() const {
    return value;
  }
};

Meaning that I would be able to use an object from the class Value like this:

Value value = const Value(value: 13.0, color: Colors.blue);

double a = value + 3; // a = 16.0
double b = value - 3; // b = 10.0
double c = value; // c = 13.0

2

Answers


  1. To achieve a similar result, you could define the addition operator + and the subtraction - operator of the Value class:

    class Value {
      final double value;
      final Color color;
    
      const Value({required this.value, required this.color});
    
      @override
      String toString() => "The value is $value.";
    
      double toDouble() => value;
    
      double operator +(num other) {
        return value + other;
      }
    
      double operator -(num other) {
        return value - other;
      }
    }
    

    Your main.dart would then become:

    void main() {
      final value = Value(value: 13.0, color: Colors.blue);
      double a = value + 3; // a = 16.0
      double b = value - 3; // b = 10.0
      double c = value.toDouble(); // c = 13.0
      double d = value.value; // d = 13.0
    }
    
    
    Login or Signup to reply.
  2. you can get similar functionality by defining methods in your class to perform these operations.

    class Value {
      final double value;
      final Color color;
    
      Value({required this.value, required this.color});
    
      double add(double operand) => this.value + operand;
      double subtract(double operand) => this.value - operand;
      double toDouble() => this.value;
    }
    
    void main() {
      Value value = Value(value: 13.0, color: Colors.blue);
    
      double a = value.add(3); // a = 16.0
      double b = value.subtract(3); // b = 10.0
      double c = value.toDouble(); // c = 13.0
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search