DWScript provides two powerful features to make your code more readable and to extend existing types without using inheritance.
Any function can be called as if it were a method of its first parameter. This leads to cleaner, more readable code that can be easily chained.
var s: String = ' hello ';
// Standard style: UpperCase(Trim(s))
// Method style:
PrintLn(s.Trim.UpperCase); // "HELLO"
var i: Integer = 255;
PrintLn(i.ToHexString(4)); // Equivalent to IntToHex(i, 4) HELLO 00FF
This works because the compiler automatically maps the call x.Method(y) to Method(x, y) if a standalone function exists where the first parameter matches the type of x.
Most basic types in DWScript have built-in helpers that provide convenient method aliases for standard library functions.
| Type | Common Methods | Equivalent Function |
|---|---|---|
| Integer | ToString, ToHexString, ToBin |
IntToStr, IntToHex, IntToBin |
| Float | ToString, ToString(p) |
FloatToStr |
| String | ToInteger, ToFloat, ToJSON, ToHtml |
StrToInt, StrToFloat, StrToJSON |
| Boolean | ToString |
BoolToStr |
Helpers allow you to explicitly extend existing classes, records, and even basic types with new methods and properties.
type
TUser = class
Name: String;
constructor Create(n: String); begin Name := n; end;
end;
type
TUserHelper = class helper for TUser
procedure Greet;
begin
PrintLn('Hello, ' + Name);
end;
end;
var u := new TUser('Alice');
u.Greet; Hello, Alice
You can extend primitive types like Integer, Float, or String to enable fluent syntax.
type
TIntHelper = record helper for Integer
function Squared: Integer;
begin
Result := Self * Self;
end;
end;
var n := 10;
PrintLn(n.Squared.ToString); // "100" 100
You can map existing functions as methods using the helper keyword in the function declaration.
function StringLength(s: String): Integer; helper Size;
begin
Result := Length(s);
end;
var s := 'Hello';
PrintLn(s.Size.ToString); // 5 5