Created
April 27, 2020 21:36
-
-
Save munificent/0831b3121652f96151d4ca9ad6c64d28 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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