Created
April 26, 2021 20:18
-
-
Save talamaska/4fb495e91b44a312138953dd8cc669d4 to your computer and use it in GitHub Desktop.
Function arguments are contravariant (whereas generics are covariant)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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