[fpc-pascal] Traits Proposal

Martin Frb lazarus at mfriebe.de
Thu Feb 18 20:33:06 CET 2021


On 18/02/2021 18:46, Ryan Joseph via fpc-pascal wrote:
>
>> On Feb 18, 2021, at 10:40 AM, Benito van der Zander via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>>
>> Traits are like reverse type helpers. With the type helper you first declare the class and then the extending helper.
> Indeed, but with the crucial distinction that helpers don't allow fields, only methods.
>
And they are differently scoped.


There is another approach, but generics do not yet support that

type
   TFooBase = class
   end;

   TTrait = trait
     procedure Bar;
   end;

   TFoo = class(TFooBase)
     _trait: TTrait;
      procedure Foo;
   end;

could be written as

   generic TTrait<T> = class(T)
     procedure Bar;
   end;

   TMyFoo = class(specialize TTrait<TFooBase>)
      procedure Foo;
   end;

Of course that can get out of hand, if you want to include many traits.

---------

On the other hand, it even would allow support for the Trait to access 
methods from TFoo...

   generic TTrait<TBase, THost> = class(TBase)
     procedure Bar; // can do    THost(self).Foo()
   end;

   TMyFoo = class(specialize TTrait<TFooBase, TMyFoo>)
      procedure Foo;  // can call Bar()
   end;

Of course assuming that TMyFoo can already be passed during specialization.




More information about the fpc-pascal mailing list