Why does toString() exist? It seems useless.

Don nospam at nospam.com.au
Wed Aug 20 08:34:34 PDT 2008


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.


More information about the Digitalmars-d-learn mailing list