Neat thing about modern Delphi

We have a custom type – TKMPoint. That type is basically a pair of values X and Y. In older days when we wanted to add two points together (for example defense position and unit position within the group) we needed to write it like so:

// Sum up parts and make that a new point
ResultingPosition := KMPoint(GroupPos.X + UnitPos.X, GroupPos.Y + UnitPos.Y);

// Or make a custom function to add two points together
ResultingPosition := KMPointAdd(GroupPos, UnitPos);

Now when we can drop Delphi 7 support, we can use a handy language feature that allows to override operators, so we can simply write:

ResultingPosition := GroupPos + UnitPos;

and that works because compiler automatically substitutes the + operator for TKMPoint with a function:

class operator TKMPoint.Add(const A, B: TKMPoint): TKMPoint;
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;

In other words – adding points together became simple and neat 🙂

This entry was posted in Sidenotes. Bookmark the permalink.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.