Custom Class Operators Demo
<?pas
// Custom Class Operators Demo
// Example 1: Custom 'in' operator for range checking
type
TDateRange = class
StartDate, EndDate: Float;
constructor Create(s, e: Float);
begin
StartDate := s;
EndDate := e;
end;
function Contains(d: Float): Boolean;
begin
Result := (d >= StartDate) and (d <= EndDate);
end;
class operator in Float uses Contains;
end;
var q1 := TDateRange.Create(
EncodeDate(2024, 1, 1),
EncodeDate(2024, 3, 31)
);
var testDate := EncodeDate(2024, 2, 15);
if testDate in q1 then
PrintLn('Date is in Q1 2024');
// Example 2: Custom '+=' for fluent building
type
TQueryBuilder = class
FSql: String;
procedure AddClause(clause: String);
begin
if FSql <> '' then FSql := FSql + ' ';
FSql := FSql + clause;
end;
class operator += String uses AddClause;
end;
var query := TQueryBuilder.Create;
query += 'SELECT *';
query += 'FROM users';
query += 'WHERE active = 1';
PrintLn('Query: ' + query.FSql);
// Example 3: Custom 'not in' automatically works
var otherDate := EncodeDate(2024, 5, 1);
if otherDate not in q1 then
PrintLn('May 1st is NOT in Q1');
?>
Date is in Q1 2024 Query: SELECT * FROM users WHERE active = 1 May 1st is NOT in Q1