Skip to content

Instantly share code, notes, and snippets.

@munificent
Created April 27, 2020 21:36
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 munificent/0831b3121652f96151d4ca9ad6c64d28 to your computer and use it in GitHub Desktop.
Save munificent/0831b3121652f96151d4ca9ad6c64d28 to your computer and use it in GitHub Desktop.
// Function parameter types are in a "contravariant position", so allowing this
// override would break soundness. Consider:
class Base {
final String Function(dynamic val) validator;
}
class Derived extends Base {
String Function(String val) validator;
}
main() {
// Upcast a Derived to a Base:
Base b = Derived();
// Call the function with wrong type:
b.validator(1234); // Oops!
}
// Because function parameters are contravariant, the "reverse" the direction
// of variance that you are allowed to use. So an override cannot tighten a
// parameter type, but it can loosen it:
class Base {
final String Function(int val) validator;
}
class Derived extends Base {
String Function(num val) validator;
}
main() {
// Upcast a Derived to a Base:
Base b = Derived();
// Always safe since the base class has the more precise type:
b.validator(1234);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment