Why does toString() exist? It seems useless.
Sean Kelly
sean at invisibleduck.org
Wed Aug 20 12:59:17 PDT 2008
Don wrote:
> Robert Fraser wrote:
>> Benji Smith wrote:
>>> Don wrote:
>>>> I cannot understand the rationale for a toString() member function
>>>> which doesn't support formatting.
>>>
>>> I agree.
>>>
>>> In Java, the toString() method *must* exist on the base Object class,
>>> because of constructs like this:
>>>
>>> String s = "hello" + (new World());
>>>
>>> Without an implementation of toString(), it'd be impossible to
>>> support those kinds of automatic String conversion and concatenation
>>> (which actually do end up being pretty handy in logging & debugging
>>> statements).
>>>
>>> But since D doesn't support implicit String conversion, it seems
>>> pretty pointless.
>>
>> I think both Tango and phobos allow objects to be converted to strings
>> when specified as parameters to a formatting function -- i.e.
>> Stdout.format("{0}", obj) will call obj.toString().
>
> And that's the problem -- it's a really poor design, totally unsuitable
> for that purpose.
>
> Simple challenge:
>
> class Foo {
> public:
> double x;
> }
>
> 1. You want it to output x in the default way for the current locale.
> (eg, 5,35 or 5.35 depending on which country you're in).
> Write toString().
> 2. Now write toString() such that:
>
> double y = 3.156892123;
> Foo z = new Foo;
> z.x = 3.156892123;
> writefln("%.3f, %.3f", y, z);
> writefln("%.4f, %.4f", y, z);
>
> (or Tango equivalent) produces the same results for y and z.
>
> Both of these should be trivial.
We had actually asked for some compiler changes to support this sort of
formatting (necessary since the function signature for toString is
hardcoded in the compiler for structs), but the request was denied,
presumably as unnecessary. I don't remember the details of the request
however--Lars would have to provide that.
Sean
More information about the Digitalmars-d-learn
mailing list