Skip to content

Instantly share code, notes, and snippets.

@Pajn
Created October 31, 2015 14:42
Show Gist options
  • Save Pajn/f14763e628abe0634a8b to your computer and use it in GitHub Desktop.
Save Pajn/f14763e628abe0634a8b to your computer and use it in GitHub Desktop.
interface MathOperators {
int add(int a, int b);
int subtract(int a, int b);
}
int calculate(MathOperators operators, int a, int b) {
return operators.add(a, operators.subtract(a, b));
}
class IntegerMath {
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;
}
class DoubleMath {
double add(double a, double b) => a + b;
double subtract(double a, double b) => a - b;
}
class OnlyAdd {
int add(int a, int b) => a + b;
}
// Okay becouse IntegerMath satisfies the interface MathOperators.
// Note that IntegerMath does not explicitly implement MathOperators, it may be defined
// in the standard lib or in anothert package that does not know that MathOperators exist
calculate(new IntegerMath(), 5, 2);
// Not okay becouse the types of the methods is invalid
calculate(new DoubleMath(), 5, 2);
// Not okay becouse the method subtract is missing
calculate(new OnlyAdd(), 5, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment