3

Why does this not work? I get a E2511 Type parameter 'T' must be a class type?

type
  IBaseProvider<T> = Interface
    function GetAll: TObjectList<T>;
  end;

type
  TCar = class(TInterfacedPersistent, IBaseProvider<TVehicle>)
    function GetAll: TObjectList<TVehicle>;
  end;

implementation

function TCar.GetAll: TObjectList<TVehicle>;
begin
  // do something with Objectlist
  Result := ObjectList
end;

1 Answer 1

3

The parameter T of TObjectList<T> is constrained to be a class.

type
  TObjectList<T: class> = class(TList<T>)
    ....
  end;

You need to declare a constraint that implies this on your type. For example you can declare the same constraint:

type
  IBaseProvider<T: class> = Interface
    function GetAll: TObjectList<T>;
  end;

Or you could declare a stronger constraint, so long as the TObjectList<T> constraint is met. If you don't want to constrain your parameter, then you'd need to use TList<T>.

If you are not familiar with generic constraints, the documentation should fill in the gaps : http://docwiki.embarcadero.com/RADStudio/en/Constraints_in_Generics

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, David. But what about TDictionary. in java I can write: HashMap<String, IBaseProvider<?>> dataproviders = new HashMap<String, IBaseProvider<?>>();. How to write in delphi??
That's a different question. Let's finish this question first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.