Search code examples
delphitypesdeclarationlazarus

How do i declare a function which takes a variable of a yet unidentified type as parameter


the question is as the title reads. O get the error: Type identifier expected, which (i think) comes from the function declaration being read before the type declaration.

type
  TForm1 = class(TForm)
    //other declarations
    function ItemThere(x: TItem): boolean; // here it says TItem is unknown
  end;

type
  TItem = class
    Name : String;
    Description : String;
    constructor Create;
  end;

Also i would like let you know that i am a rather unexperienced programmer. How can i fix this? Should i just move the declaration of TItem above TForm1? Thank you for your help.


Solution

  • Delphi's compiler needs to know about the type before it's used. There are two ways to accomplish that with your code.

    1. Move the declaration above the place it's first used:

      type
        TItem = class
          Name : String;
          Description : String;
          constructor Create;
        end;
      
        TForm1 = class(TForm)
          //other declarations
          function ItemThere(x: TItem): boolean; 
        end;
      
    2. Use what is known as a forward declaration, which basically just tells the compiler that you're using a class which you'll define later (within the same type declaration section):

      type
        TItem = class;              // forward declaration
      
        TForm1 = class(TForm)
          //other declarations
          function ItemThere(x: TItem): boolean; 
        end;
      
        TItem = class               // Now define the class itself
          Name : String;
          Description : String;
          constructor Create;
        end;