Recent

Author Topic: Playing around with properties  (Read 398 times)

JdeHaan

  • Full Member
  • ***
  • Posts: 171
Playing around with properties
« on: May 02, 2025, 11:43:57 am »
This is not a question. I just wanted to share this code, of which I wasn't aware that this was possible in FP. Especially, the way the record is created/initialized, using a property instead of a constructor.

Code: Pascal  [Select][+][-]
  1. program Project1;
  2. {$Mode Delphi}
  3.  
  4. type
  5.   TTimesTable = record
  6.     private
  7.       fMultiplier: Integer;
  8.       function Init(Multiplier: Integer): TTimesTable;
  9.       function Multiply(Value: Integer): Integer;
  10.     public
  11.       property Multiplier: Integer read fMultiplier;
  12.       property Create[Multiplier: Integer]: TTimesTable read Init;
  13.       property Item[Value: Integer]: Integer read Multiply; default;
  14.   end;
  15.  
  16.  
  17. { TTimesTable }
  18.  
  19. function TTimesTable.Multiply(Value: Integer): Integer;
  20. begin
  21.   Result := Value * fMultiplier;
  22. end;
  23.  
  24. function TTimesTable.Init(Multiplier: Integer): TTimesTable;
  25. begin
  26.   fMultiplier := Multiplier;
  27.   Result := Self;
  28. end;
  29.  
  30. var
  31.   Table: TTimesTable;
  32.   n: Integer;
  33.  
  34. begin
  35.   Table.Create[7];
  36.   WriteLn('Table of ', Table.Multiplier, ':');
  37.   for n := 1 to 10 do
  38.     WriteLn(n:2, ' x ', Table.Multiplier, ' = ', Table[n]:2);
  39. end.
  40.  

Thaddy

  • Hero Member
  • *****
  • Posts: 18943
  • Glad to be alive.
Re: Playing around with properties
« Reply #1 on: May 02, 2025, 12:13:17 pm »
Two remarks:
1. It is a record
2. A property can be named as - almost - anything, you just happened to call it create.

But yes, this is completely legal code.
« Last Edit: May 02, 2025, 12:17:00 pm by Thaddy »
Recovered from removal of tumor in tongue following tongue reconstruction with a part from my leg.

 

TinyPortal © 2005-2018