[fpc-pascal] Chaining method calls

George Bakhtadze armorcavalry at yandex.com
Tue Mar 24 18:23:44 CET 2020


Hi.

You can have such ID if you will use generics:

{$mode Delphi}
type
  TBase<T: class> = class
  public
    function AndThis: T;
  end;

function TBase<T>.AndThis: T;
begin
  result := self as T;
end;

type
  TMyClass = class;
  TMyClass = class (TBase<TMyClass>)
  end;

var
  c: TMyClass;
begin
  c := TMyClass.Create.AndThis;
  writeln(c.classname);
end.

Don't know how to write it with objfpc style generics but I believe it's possible.


24.03.2020, 16:55, "Ryan Joseph via fpc-pascal" <fpc-pascal at lists.freepascal.org>:
> True, but then we're stuck in a typecasting game where I need to cast "c" back to TMyClass. :) I probably brought this up years ago and forgot but Objective-C has an "id" type which is "can assign to any class type". It seems like something that would be standard for OOP but I don't recall ever seeing it in Pascal or C++.

---
Best regards, George


More information about the fpc-pascal mailing list