dart-lang / dart-lang/language

Inherent extensions

Open
#3,220 3 comments 0 reactions 0 assignees View on GitHub
feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

When designing an API that includes usage of private fields that are exposed publicly in some form, it is generally undesirable to allow polymorphism on some members. Take the following example:

```dart
// Assume we're using some new nifty features for brevity purposes.
abstract base class Node<
N extends Self,
P extends Node<_, _, N>,
C extends Node
> {
P? _parent;
C? _firstChild;
C? _lastChild;
N? _previous;
N? _next;

Node.detached();

void reparent(N parent) {
// ... this implementation is VERY important
}
}
```

A subtype can override reparent! That's not good, something like this should be statically dispatched.

The workaround today is to place it in a separate extension, but that doesn't play well with `import '...' show Node;`.

I propose that extension methods and bodies be allowed within classes:

```dart
abstract base class Node<...> {
extension void reparent(N parent); // Like an extension on Node<...> but is always visible.
extension on Node {
// Bodies are supported, with refinement typing. Just no extensions with names.
}
}
```

For extension disambiguation, extension members require a cast: `(node as Node).reparent(parent)`

Contributor guide

Open the contributing guide

Research direction

This is a Dart language-design proposal for allowing extension members and bodies inside classes; no implementation files, tests, or entry points are named. Start by reviewing the proposal and its visibility and disambiguation requirements, and consider the feature complete only when its syntax, semantics, and specification impact are resolved.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.