Francesco Iapicca
Francesco Iapicca

Reputation: 2667

Inconsistent behavior between class and typedef

the code below gives an error, assuming that it's intended and not a bug

class Bar {}

class Baz extends Bar {}

typedef Foo<T extends Bar> = void Function(T);

void printBaz(Baz baz) => print(baz);

final list = <Foo>[];

class Fiz<T extends Bar> {
  final T data;
  Fiz(this.data);
}

void main(){
  final fiz = Fiz(Baz()); /// of course no problem!
  
  list.add(printBaz); 
  /// The argument type 'void Function(Baz)' can't be assigned to the parameter type 'void Function(Bar)
}

can anyone explain me the reason of this behavior
that seems to be inconsistent across typedef and class

also a way to circumvent the error will be appreciated

Upvotes: 1

Views: 27

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17141

This is expected behavior. It has to do with the typing on your list. Since you do not specify the generic when you declare the list, only specifying any Foo, the inferred type is a List<Foo<Bar>>, because Bar is the most generic type you allow Foos to take.

printBaz does not know how to handle a Bar parameter, therefore it cannot be added to your list and you get a linter error.

This can be solved by providing the generic argument on Foo when you declare and initialize your list:

final list = <Foo<Baz>>[];

Upvotes: 3

Related Questions