- DelphiTools - https://www.delphitools.info -

The case for strict parameter types

While refactoring a bit the way some “special” functions were handled in DWScript, I came about a case where the compiler started accepting strings as Math functions parameters.

While this comes naturally as an “interesting” side-effects of automatic typecasts, it left a feeling of “wrongness”, accepting literal code like Abs(“foo”) and then failing at run-time is asking for trouble.

Hence the introduction of an experimental strict type qualifier for function parameters, which will forbid automatic typecasts. This means you can now write code like

function OnlyFloats(f : type Float) : Float;

The extra “type” before the parameter denotes a strict type check with forbidden automatic typecasts, so¬†OnlyFloats() will no longer accept Integer parameters (no automatic casts).

In the case of overloaded functions, this can be used to have Integer, Float and Variant overloads, without the Variant overload resulting in String being accepted through automatic boxing:

function OnlyNumerics(f : type Float) : Float; overload;
function OnlyNumerics(f : type Integer) : Integer; overload;
function OnlyNumerics(f : type Variant) : Variant; overload;

The idea here being to deter problematic (mis)uses of a function or method by providing more compile-time control.

Note that when used with parameters of a class type, sub-classes of that class will still be accepted (as there is no typecasting in that case, only a type check).

Note that this feature is still experimental at the moment, and subject to change.

There is awlays an xkcd !