25

I have just take a look at the 3ΒΊ tutorial from dart, creating the rating component. I was wondering if there is same method which is called when stringifying an object, something similar to Java's toString.

For example:

MyClass myObject = new MyClass();
System.out.println(myObject);

Will call MyClass.toString() if overwriten, else will call it's parent until java.lang.Object is reached giving a default toString.

I find kind ugly (completely subjective) doing:

<span ng-repeat="star in cmp.stars" > {{star.toString()}} </span>

I would rather do:

    <span ng-repeat="star in cmp.stars" > {{star}} </span>

And give the implementation of how I want it to display at an averwritten method. Is this possible?

Javier Mr
  • 2,130
  • 4
  • 31
  • 39

3 Answers3

29

If you have something like this:

class MyClass {
    String data;

    MyClass(this.data);

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

MyClass myObject = new MyClass("someData");
print(myObject); // outputs "someData", not 'Instance of MyClass'

I think this might be what you are looking for.

dgp
  • 953
  • 1
  • 8
  • 11
20

Yes it works like this for print, String interpolation or Angular mustaches.

By overriding the String toString() method on your object the displayed value will be the result of this toString() call. If there's no toString() defined in the class hierarchy the toString() of Object will be called (which will return Instance of 'MyClass' for class MyClass{}).

Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
1

You may be interesting look how Rating component was implemented in Angular Dart UI project. Check this out.

Sergey.

akserg
  • 436
  • 2
  • 4
  • Wow, cool component. I'm still in the angular tutorial series, but clearly the next one will be angular dart ui. – Javier Mr Apr 09 '14 at 17:49