Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use two record helpers for the string type?

I created this helper in order to add some more functions to the string type:

type
  AStringHelper = record helper for string
    function Invert: string; overload;
    function InvertMe: string; overload;
  end;

But when I use it in my code, the TStringHelper in System.StrUtils "gets out" and I can't use it's functions.

Is it possible to both of them to coexist?

like image 621
NaN Avatar asked Jul 27 '13 15:07

NaN


3 Answers

Another possibility is to use the "Ancestor list" option offered by helpers

Syntaxis:

type
identifierName = class|record helper [(ancestor list)] for TypeIdentifierName
  memberList
end;

And use like this:

Unit1:   
THelperBase = Class helper for TMyClass
Public
  Function SayHello;
end;

Unit2:
Uses Unit1;
THelperChild = Class helper (THelperBase) for TMyClass
Public
  Function SayGoodBye;
end;

And finally, in your code:

Uses Unit2;   

Var MyClass: TMyclass;   

MyClass:= TMyclass.Create;
MyClass.SayHello; //valid
MyClass.SayGoodBye; //valid
like image 142
GatoSoft Avatar answered Nov 16 '22 13:11

GatoSoft


At most one helper can active at any one point in your code. The documentation says this:

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).

Since record helpers do not support inheritance, there's no way to have both the standard helper's and your helper's functionality active at the same time, other than re-implementing the standard helper's functionality.

like image 13
David Heffernan Avatar answered Nov 16 '22 13:11

David Heffernan


Try to create your own class and helper

TMyString = type string;
TMyStringHelper = record helper for TMyString 
  function Invert: TMyString; 
  function ToString: string;
end;

Use TMyString instead of String.

To use standard String helpers wrap TMyString variable with String() or use ToString method.

var
  S1: TMyString;
  S2: String;
begin
  S1 := ' 123456 ';
  S1.Invert;
  S2 := String(S1).Trim;
  S2 := S1.ToString.Trim;
end;
like image 5
Sergio Barbery Avatar answered Nov 16 '22 14:11

Sergio Barbery