Why does toString() exist? It seems useless.

Benji Smith dlanguage at benjismith.net
Mon Aug 18 10:21:17 PDT 2008


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.

Incidentally, I'd be opposed to a toString(char[] format) method being a 
part of the Object class. I prefer the Tango (.NET style) formatting, 
and others surely prefer the printf style formatting in Phobos. If 
formatting strings became a part of the basic Object definition, I can 
imagine a lot of very annoyed developers, depending on which formatting 
style was chosen for Object.

--benji


More information about the Digitalmars-d-learn mailing list