Let’s say we have interface I, object O and a container sl:
type
rootInterface = Interface
end;
childOfRootInterface = interface(rootInterface)
end;
ObjectImplementsRootInterface = class(TObject, I)
end;
ObjectImplementsChildOfRootInterface = class(TOtherObject, I2);
end;
var
aStringList: TStringList;
Assuming that sl is initialized.
If we do
aStringList.Items.AddObject('root', ObjectImplementsRootInterface );
then we can’t do
ObjectImplementsRootInterface := I(aStringList.Items.Objects([0]));
because Delphi forbids this. so trying:
ObjectImplementsRootInterface := TObject(aStringList.Items.Objects([0]));
However, we inserted an childOfRootInterface and we want back an childOfRootInterface so we do
ObjectImplementsChildOfRootInterface := childOfRootInterface (sl.Items.Objects([0]));
But ObjectImplementsChildOfRootInterface and ObjectImplementsRootInterface have different supers!
Although they support the same interface, we can’t do anything.
In java you can pass around objects, as long as they support interface, In java it would be possible, so now after all this planning; what can I do in Delphi?
Update: changed the names, however the example might got over me and won, can’t find right and left.
Here is a working code example:
To avoid a hard type cast I use a GUID for the interface.
Supports can be used for a safe test and assignment of the object to a variable of type I. Note that type names are a bit confusing in your example.
Hard typecasting to an interface is not possible for items in the object list.