Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi helpers scope

I have a problem with helper re-declaration in Delphi.

HelperDecl.pas

unit HelperDecl;

interface

type
  TCustomField = Word;

  TCustomFieldHelper = record helper for TCustomField
  public
    procedure SampleMethod();
  end;

implementation

procedure TCustomFieldHelper.SampleMethod();
begin
end;

end.

ScopeTest.pas

unit ScopeTest;

interface

uses HelperDecl;

type
  rec = record
    art: TCustomField;
  end;

implementation

uses System.SysUtils;

procedure DoScopeTest();
var
  a: TCustomField;
  r: rec;
begin
  a := r.art;
  r.art.SampleMethod(); //Here has the compiler no problems
  a.SampleMethod(); //Undeclared identifier 'SampleMethod'
end;

end.

But I have defined a helper only for my local data type (yes, it is derived from Word)! The helper in SysUtils is the helper for Word, not for my custom data type! Hands off my data type!

When I move uses System.SysUtils; before uses HelperDecl; then it works. But I would like to have an arbitrary units usage order.

like image 932
Paul Avatar asked Sep 17 '20 09:09

Paul


2 Answers

The problem is that TCustomField and Word is the same type and it is not possible to have two record helpers for the same type.

If you instead let TCustomField by a distinct type, it will work:

type
  TCustomField = type Word;
like image 185
Andreas Rejbrand Avatar answered Nov 13 '22 03:11

Andreas Rejbrand


Delphi only supports single helper. When you have multiple helpers in scope, helper from nearest scope is used.

You can define and associate multiple helpers with a single type. However, only zero or one helper applies in any specific location in source code. The helper defined in the nearest scope will apply. Class or record helper scope is determined in the normal Delphi fashion (for example, right to left in the unit's uses clause).

Class and Record Helpers

like image 3
Dalija Prasnikar Avatar answered Nov 13 '22 03:11

Dalija Prasnikar