Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler complain "incompatible types" for my generic function parameter?

I am having problems with generics. I do not know how to pass OnCallbackWrapper to the CallbackWrapper procedure. I am getting 'incompatible types' error on the following example:

unit uTest;

interface

uses
  Generics.Defaults;

type
  TGenericCallback<T> = procedure(Fields: T);

type
  TSpecificFields = record
    A: Integer;
    B: Integer;
    C: Integer;
  end;

const
  SpecificFields: TSpecificFields =
  (A: 5; B: 4; C: 3);

procedure CallbackWrapper(GenericCallback: TGenericCallback<TSpecificFields>);

implementation

procedure CallbackWrapper(GenericCallback: TGenericCallback<TSpecificFields>);
begin
  GenericCallback(SpecificFields);
end;

procedure OnCallbackWrapper(const Fields: TSpecificFields);
begin
  Assert(Fields.A = 5);
  Assert(Fields.B = 4);
  Assert(Fields.C = 3);
end;

procedure Dummy;
begin
  CallbackWrapper(OnCallbackWrapper); //Incompatible types here
end;

end.

What am I doing wrong? Thanks.

like image 937
Wodzu Avatar asked Dec 06 '22 10:12

Wodzu


1 Answers

The type that you declared receives its parameter by value.

TGenericCallback<T> = procedure(Fields: T); // no const

The function you pass is marked with const.

procedure OnCallbackWrapper(const Fields: TSpecificFields); // const parameter

So the compiler rejects the parameter you attempt to pass as not matching. You need to make both sides match. For example:

TGenericCallback<T> = procedure(const Fields: T);
like image 56
David Heffernan Avatar answered Jan 04 '23 23:01

David Heffernan