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

断了今生、忘了曾经 提交于 2020-07-29 09:51:17

问题


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?


回答1:


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




回答2:


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.




回答3:


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

Sergey.



来源:https://stackoverflow.com/questions/22921222/default-stringify-for-objects-equivalent-to-javas-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!