On 2012-12-04 09:22, Maxim Fomin wrote:

And what happens if nobody implements an interface?

import std.stdio;

interface I { }

class A { }

void main()
{
     I i;
     // assume this is implicit
     Object o = cast(Object)i;
     writeln(typeid(o));
}

You get a segmentation fault since both "i" and "o" are null.

Safe conversion class to interface requires two conditions:
1a) that class implements interface
1b) if you try to use interface variable, it must be an allocated class
instance

Safe conversion to Object requires:
2a) somebody in class hierarchy implements interface
2b) interface instance is actually allocated class instance

You cannot really get an instance of an interface without having a class implementing it. That is, without inserting any explicit casts, which works:

interface I { }

class A { }

void main()
{
    A a = new A;
    I i = cast(I) a;
    Object o = cast(Object)i;
    writeln(typeid(a)); // A
}

It is possible to check 1a) but impossible in general case to check 2a).
Also the first is design feature while the second is design abuse.

I don't understand why it wouldn't be safe to allow implicit casts of interfaces to Object.

If I want to call toString, why should I need to insert an explicit cast to Object just because I have an interface?

--
/Jacob Carlborg

Reply via email to