D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 535 - writef doesn't work on interfaces
Summary: writef doesn't work on interfaces
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D1 (retired)
Hardware: x86 All
: P2 normal
Assignee: Andrei Alexandrescu
URL:
Keywords:
: 2200 (view as issue list)
Depends on:
Blocks:
 
Reported: 2006-11-16 18:44 UTC by Stewart Gordon
Modified: 2014-02-15 13:28 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Stewart Gordon 2006-11-16 18:44:35 UTC
If writef is fed an argument of an interface type, it just throws a FormatError.

----------
import std.stdio;

interface Qwert {}

class Yuiop : Qwert {
    char[] toString() {
        return "asdfg";
    }
}

void main() {
    Qwert hjkl = new Yuiop;

    writefln(hjkl);
    writefln("%s", hjkl);
}
----------
Error: std.format formatArg
----------

It should use the object's toString property.  True, interfaces don't extend Object and so don't have toString as such, but what could be more sensible than casting it to an Object and then treating it in the same way?

Adding char[] toString() to the interface makes no difference.
Comment 1 Bill Baxter 2007-12-05 23:41:05 UTC
I'd say this is an outright bug.  It can't cast to Object because it could be a COM interface, but if the interface explicitly has a toString method, then writef should definitely call it rather than throwing an exception.
Comment 2 Stewart Gordon 2007-12-06 13:04:42 UTC
Surely it's not being a COM _interface_, but being a COM _object_ external to D that would be a problem, right?

I suppose the question is whether the runtime can determine if it's a D object.  If so, the TypeInfo for interfaces could define this behaviour:  If the interface defines a suitable toString, use it.  Otherwise, see at runtime whether the interface instance is a D object.  If so, convert it to an Object and use its toString, otherwise throw an exception.

If this runtime checking isn't possible (or isn't worth the implementation cost), then having a documented requirement that the interface defines a toString for it to work is a possibility, but it still has its drawbacks....
Comment 3 David Simcha 2009-03-27 19:43:52 UTC
*** Bug 2200 has been marked as a duplicate of this bug. ***
Comment 4 Andrei Alexandrescu 2010-09-13 19:44:38 UTC
http://www.dsource.org/projects/phobos/changeset/1996