Description
In the extension struct proposal (#2360) I allow extension structs to implement class interfaces, in the case that their representation type implements the interface. This allows extension structs to expose the fact that the underlying representation implements an interface. Extension structs are forbidden from providing their own implementation for methods exposed via interfaces in this manner, to avoid the surprising behavior that such methods are statically dispatched, and hence any dispatch of interface methods through the interface will continue to reach the original implementation from the underlying object. Example:
extension struct Nat(int x) implements Comparable<num> {
int compareTo(num other) => -(x.compareTo(other));
}
void compare<T>(Comparable<T> first, Comparable<T> snd) {
print(first.compareTo(snd));
}
void test() {
Nat n = Nat(3);
Nat m = Nat(2);
print(n.compareTo(m)); // prints "1"
compare(n, m); // prints "-1";
}
This is surprising, and it seems to me to be even more surprising than in the extension case (#2369), since rather than extending a struct, we are here claiming to implement a class interface. The primary use of interfaces is to support writing code which is polymorphic over interfaces, allowing declarations to provide their own implementations. With extension structs however, the provided implementations are never used when accessed via that interface. In contrast, extension provides both polymorphism and inheritance, and extension structs are never polymorphic.