[fpc-pascal] Traits Proposal
Michael Van Canneyt
michael at freepascal.org
Wed Feb 10 08:32:13 CET 2021
On Tue, 9 Feb 2021, Ryan Joseph via fpc-pascal wrote:
> We had talked about this some time ago and it's been rattling around in my brain so I wanted to write it down into a formal proposal where we can discuss it and hopefully agree upon a syntax. Everything is preliminary and tentative but this is a syntax which allows a "composition over inheritance" model, also known as "mix-ins" in some languages. That idea is similar to multiple inheritance except you have a concrete reference to the trait being implemented so you can resolve conflicts easily.
>
> Here's what I have so far. Please feel free to look at it and give any feedback.
>
> https://github.com/genericptr/freepascal/wiki/Traits-Proposal
In general, I am charmed by this idea.
But I don't see the need to extend/change existing syntax, and in fact I highly
object to it.
Instead of trait you might as well use simply "object", so basically we
could simply state that instead of an interface, you can also specify an object
in the class definition:
TMyClass = class (TParent,TMyTrait1,TMyTrait2)
Public
property Trait1: TMyTrait1 read FTrait1 implements TMyTrait1;
property Trait2: TMyTrait2 read FTrait2 implements TMyTrait2;
end;
So no syntax changes are needed. Any restrictions on the objects in the
"traits" can be handled by the compiler.
The only difference with Interfaces is that you MUST have a property with
'Implements' if you specify an object. If you do not, the compiler complains.
It will also automatically mean that you can only have 1 trait of a certain
type, since the
TMyClass = class (TParent,TMyTrait1,TMyTrait2)
cannot contain duplicates.
I also don't think you should forbid constructors; In fact I think they are
necessary if you want to support polymorphism, because I think they create/set the VMT ?
(the compiler people need to confirm this)
The only obvious thing missing in your proposal is how this changes the RTTI of the
objects.
Michael.
More information about the fpc-pascal
mailing list