Description
Dart SDK version: 3.8.0-149.0.dev (dev) (Thu Feb 27 04:01:43 2025 -0800) on "macos_x64"
In the same folder:
lib1.dart
class Super
{ final _secret='🤫';
@override void shareSecrets(final Super other)
{ print('This secret is $_secret.');
print('Other\'s secret is ${other._secret}.');
}
}
lib2.dart
import 'lib1.dart';
void main()=>
Super().shareSecrets(Implementer());
final class Implementer implements Super
{ @override void shareSecrets(final Super other)=>
other.shareSecrets(this);
}
Do dart run lib2.dart
and observe the output (stack trace omitted)
This secret is 🤫.
Unhandled exception:
NoSuchMethodError: Class 'Implementer' has no instance getter '_secret'.
Receiver: Instance of 'Implementer'
Tried calling: _secret
This exception makes sense, the issue is not about that. The concern is that there is no indication that it is incorrect for the implementer to be used as a Super
in certain cases.
It is natural to believe if one implements a type and it fulfills its contractual obligations through its API, then it must work wherever that type is expected, because it (1) is that type, and (2) is successfully implemented to function as that type.
Solution
Currently, even adding a _secret
field to the implementer does not work. That makes sense because the implementer may happen to have a private field that is semantically different than the super type's field.
It would be better if there were some form of warning or restrictions in place.