Skip to content

Instantly share code, notes, and snippets.

@talamaska
Created April 26, 2021 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save talamaska/4fb495e91b44a312138953dd8cc669d4 to your computer and use it in GitHub Desktop.
Save talamaska/4fb495e91b44a312138953dd8cc669d4 to your computer and use it in GitHub Desktop.
Function arguments are contravariant (whereas generics are covariant)
/// quick question about Something<T extends SomethingElse>
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)
}
/// This is intended behavior, function arguments are contravariant (whereas generics are covariant)
/// That means a Function(num) is assignable to Function(int), instead of the other way around
/// How to circumvent this?
/// something like
void main(){
final fiz = Fiz(Baz());
list.add((baz) => printBaz(baz as Baz))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment