[fpc-pascal] Traits Proposal

Martin Frb lazarus at mfriebe.de
Wed Feb 10 21:51:53 CET 2021


On 10/02/2021 21:17, Ryan Joseph via fpc-pascal wrote:
>
>> On Feb 10, 2021, at 12:40 PM, Martin Frb via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>>
>> type
>>    TSomeTrait = trait
>>    public
>>      procedure DoTraitFoo;
>>    end;
>>
>>    TSomeClass = class(TObject)
>>    private
>>      trait: TSomeTrait; // whatever syntax is used so that the trait is added
>>    public
>>      SomeVal: Integer;
>>      procedure DoSome;
>>      procedure Dispatch(var message); override;
>>    end;
> if it's the simple then just set a reference to TSomeClass inside of TSomeTrait. If the trait doesn't know anything about the implementor then you indeed need to use a dispatch table or something. Can't this be solved with existing features?
>
> btw, I don't think we should model this based on PHP, I just gave that as an example. The Swift model is much more simple and does 99% of what you want. I think that's what we should do for Pascal also.
>
I don't have a pro/contra agenda on whether that feature should be part 
of the fpc trait or not.
I just saw it, and thought I raise it.

But also, if any option should be reserved for the future, then it 
matters. Because re-using "sometrait = object end" makes it less likely 
that an "implements" clause will be added (because "object" does already 
have a fully defined syntax).
So I felled it might be worth being noted.

------
Another option would be

       TSomeTrait = trait (basetrait) for (someclass_as_minimum_base_class)

for (someclass) is of course  optional (or rather default to TObject).
So sometrait then can access
    self.any_trait_identifier
    self.someclass_ident

This is a bit limiting at first, but bring in genericts
       generic TSomeTrait = trait (basetrait) for (<T>)
Since it is a generic the compiler will not complain about unknown 
identifiers.

It can automatically specialise, when applying a trait.

Then again the "implements" clause from above could internally create a 
generic too.

----------------------
Btw, next question that just came up

Will traits only apply to classes?

or could a record / advanced record / old object also receive traits ?

------------------------
And one more thing that may at least be considered for design in case of 
future use.

Consider a Trait
TEmployeList = trait
   function  FindByUnallocateWorkTime: TEmploye;
end;

TCompany = class
end;

Now the company could have Engineers and Designers. It needs to lists....
But the trait can obviously only be added once.
Yet no-one wants to copy and paste the trait to create a 2nd verson

Maybe Something like
TDesignerList = trait(TEmployeList)
   function  FindDesigerByUnallocateWorkTime: TEmploye; aliases 
FindByUnallocateWorkTime;
end;

--------------
Again, none of those are needed. But if they are found interesting....


More information about the fpc-pascal mailing list