Default stringify for objects, equivalent to Java's toString?

Javier Mr picture Javier Mr · Apr 7, 2014 · Viewed 7.8k times · Source

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?

Answer

Alexandre Ardhuin picture Alexandre Ardhuin · Apr 7, 2014

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{}).