[fpc-pascal] Chaining method calls

Ryan Joseph genericptr at gmail.com
Tue Mar 24 06:59:12 CET 2020


Is it possible to achieve this dynamically without resorting to type casting? It feels like classes should have a builtin type for each class, like TClassType, which similar to TObject.ClassType but is a compile time type.

=========

{$mode objfpc}

program test;

type
  TBase = class
    // TClassType should be the type of the current class
    private type TClassType = ...;
    public
      function AndThis: TBase;
  end;

function TBase.AndThis: TBase;
begin
  result := self;
end;

type
  TMyClass = class (TBase)
  end;

var
  c: TMyClass;
begin
  // error: Incompatible types: got "TBase" expected "TMyClass"
  c := TMyClass.Create.AndThis;
  writeln(c.classname);
end.

Regards,
	Ryan Joseph



More information about the fpc-pascal mailing list