Records in Delphi 8 and class operators
Records in Delphi 8 has been extended. In previous versions of Delphi, records can only be defined thus,
recordTypeName = [packed] record
fieldList1: type1;
...
fieldListn: typen;
end
In Delphi 8 and later, records have been extended to read like class declarations, with inheritance implementations, except that forward record declarations cannot be made. So, records can now hold fields, properties, and events. They can also have static and nonstatic methods.
recordTypeName = [packed] record ['(' [InterfaceIdentifier]+ ')']
[scope]
fieldList1: type1;
...
fieldListn: typen;
MemberList
end
For example,
TPerson = record // note! Not a class
private
FFirstName, FLastName: string;
FOnNameSet: TNotifyEvent;
public
procedure SetFirstName(const AValue: string);
property FirstName: string read FFirstName write SetFirstName;
property OnNameSet: TNotifyEvent read FOnNameSet write FOnNameSet;
end;
In addition, records and classes have been extended, such that, you can now declare records/classes to convert from/to another type, transparently.
TDoubleInput = record
private
FValue: Integer;
public
class operator Implicit(const AValue: string): TDoubleInput;
class operator Implicit(const AValue: TDoubleInput): Integer;
end;
class operator TDoubleInput.Implicit(const AValue: string): TDoubleInput;
begin
Result.FValue := StrToIntDef(AValue, 0) * 2;
end;
class operator TDoubleInput.Implicit(const AValue: TDoubleInput): Integer;
begin
Result := AValue.FValue div 2;
end;
var
Double: TDoubleInput;
I: Integer;
begin
Double := '2'; // line 1
I := Double; // line 2
end;
In the above short segment of code, a variable of type TDoubleInput is declared.
In line 1, a string value, '2' is declared to Double. Internally, since a class operator is declared that can take a string value, that class operator is called. The class operator converts '2' to an integer, doubles it and stores the value.
In line 2, Double is assigned to an integer. Since a class operator is declared that can take a TDoubleInput, and return an integer as a result, that class operator is called. The class operator just takes the internal representation of the value, and divides it by 2.