Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces with Generics - Setting to NIL

I am trying to implement clear in the following example code in Delphi 2009.

interface
...
  TFoo<T : IInterface> = class(TObject)
    FField : T;
    procedure Clear;
  end;
...
implementation
...
procedure TFoo<T>.Clear;
begin
  // Line Below Results In
  //  E2010 Incompatible types: 'T' and 'Pointer' 
  FField := nil;
end;
...

I could understand the complie time error if "T" was not constrained. But since "T" must be an Interface, I would have thought this syntax would have worked.

Is there away to set FField to NIL, so the interface can be released?

like image 721
Robert Love Avatar asked May 25 '09 17:05

Robert Love


People also ask

CAN interface have generics?

Generic interfaces can inherit from non-generic interfaces if the generic interface is covariant, which means it only uses its type parameter as a return value.

How do you use generics with interfaces?

Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods.

Can we use generics with interface in Java?

Java Generic Interface In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.

What is a generic interface?

A generic interface is primarily a normal interface like any other. It can be used to declare a variable but assigned the appropriate class. It can be returned from a method. It can be passed as argument. You pass a generic interface primarily the same way you would an interface.


1 Answers

Instead of nil you must use the new Default(T) which returns the default value for the generic parameter type. And for interfaces it is nil

procedure TFoo<T>.Clear;
begin
  FField := Default(T);
end;
like image 187
Andreas Hausladen Avatar answered Sep 23 '22 18:09

Andreas Hausladen