dart-lang / dart-lang/language
Declare extensions methods directly in class.
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
It's possible to declare a class and an extension on that class in the same library.
Instead of requiring an extra extension, we could allow extension members to be declared directly in the class itself.
Example:
```dart
class Point {
T x;
T y;
Point(this.x, this.y);
extension double get distanceFromOrigo => sqrt(x * x + y * y);
}
```
This will introduce a `distanceFromOrigo` extension on the `Point` type, just as if you had written
```dart
extension PointExtension on Point {
double get distanceFromOrigo => sqrt(x * x + y * y);
}
```
Unlike named extensions, this particular extension cannot be disabled by not importing `Point`.
It's an inherent extension of the `Point` class, so it can always be used on something of type `Point`, even if the library doesn't directly import `Point`. (Because the extension is declared by the same author as the class it's on, it gets preferential treatment wrt. that type).
It can still be shadowed by more specific extensions or by subclass instance members.
Such inherent extension methods can be used as simple *interface default methods*. It's not a fully fletched default method feature because the methods are not virtual (proper interface default methods are).
Alternatively, we should just introduce interface default methods (#884). They would cover the same use-cases and would also be virtual.
Contributor guide
Assessment
This issue has not been assessed yet.