class Object with Dependency Injection

Ali Çehreli acehreli at yahoo.com
Sun Jun 18 16:58:15 UTC 2023


On 6/18/23 07:37, Salih Dincer wrote:

 >    auto truck = new Truck;
 >    auto ship = new Ship;
 >
 >    auto services = [ truck, ship ];

The problem is with the deduced type of 'services'. I don't know the 
mechanism behind it but the common type of 'truck' and 'ship' are 
deduced to be Object. Apparently, their interfaces don't take part in 
that decision. I don't know why.

One solution is to help the compiler by casting them to your desired 
interface:

   auto services = [ cast(ITransport)truck, cast(ITransport)ship ];

Or you can put the casts inside a function that could hide the 
complexity below:

   import std.algorithm;
   import std.range;
   auto services = [ truck, ship ].map!(s => cast(ITransport)s).array;

Ali



More information about the Digitalmars-d-learn mailing list