2

For example, the blow will output Instance of 'Point'. is it possible reformat it to sth like Point(x: 0, y: 0)?

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);
}

void main() {
  final zero = Point(0, 0);
  print(zero); // Instance of 'Point'
}

In Python, there is __repr__ and __str__ . In Java, there is toString. In Swift/ObjC, there is description. What is the equivalent in dart?

Yuchen
  • 30,852
  • 26
  • 164
  • 234

2 Answers2

5

You can overide the toString method:

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);

  @override
  String toString(){
    return "Point(x: $x, y: $y)";
  }
}

void main() {
  final zero = Point(0, 0);
  print(zero); // Point(x: 0, y: 0)
}

Which prints your wanted string.

Naslausky
  • 3,443
  • 1
  • 14
  • 24
2

Dart has a toString() method as well, similar to Java!

class TestClass {

    String blah;
    TestClass(this.blah);

    @override
    String toString() {
        return blah;
    }
}

TestClass testClass = new TestClass("test");
print(testClass); //This will output 'test' as opposed to 'Instance of TestClass'
Jason
  • 284
  • 2
  • 10