Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2019-09

for-in loop cast

5 messages · 3 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Ryan Joseph

Question I’ve always had. Why do I need to cast “value” to “pointer" otherwise I get: Incompatible types: got "Pointer" expected “TObject” error?. I don’t find this very helpful and it doesn’t really make sense even.

var
  list: TObjectList;
  value: TObject;
begin
  for pointer(value) in list do
    ;

Regards,
Ryan Joseph

Reply by email

Ben Grasset
to Ryan Joseph
AM Ryan Joseph wrote 5 lines
Question I’ve always had. Why do I need to cast “value” to “pointer" otherwise I get: Incompatible types: got "Pointer" expected “TObject” error?. I don’t find this very helpful and it doesn’t really make sense even.

Well, TObjectList is a descendant of TList, which is of course a non-generic list of void pointers. The enumerator for TList that allows the for-in loop to work, called TListEnumerator, as such obviously implements GetCurrent as returning "pointer".

TObjectList doesn't have its own enumerator implementation on top of the TList one or anything like that, so when you use for-in on TObjectList, you're using the pointer-based TList one.

The fix for this is simple IMO: use a generic list class instead. For example, if you want something that works exactly like your code example, you can specialize TObjectList from Generics.Collections literally *with* TObject:

type
  TBaseObjectList = TObjectList<TObject>;
var
  list: TBaseObjectList;
  value: TObject;
begin
  for pointer(value) in list do
    ;

Reply by email

Sven Barth
to Ryan Joseph: Question I’ve always had. Why do I need to cast “value” to “pointer" otherwise I…

Ryan Joseph schrieb am Do., 26. Sep. 2019, 17:37:

Show quoted text 12 lines
Question I’ve always had. Why do I need to cast “value” to “pointer" otherwise I get: Incompatible types: got "Pointer" expected “TObject” error?. I don’t find this very helpful and it doesn’t really make sense even. var list: TObjectList; value: TObject; begin for pointer(value) in list do ;

Aside from what Ben wrote I wonder whether such a cast should be able to compile at all... 🤔

And we should probably add a proper TObject enumerator to TObjectList.

Regards,
Sven

Reply by email