dart-lang / dart-lang/language

Add first class support for method forwarding

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

Description

It's a common pattern to wrap an interface with a `Delegating` class which forwards all methods to a instance of the same interface and allows selectively overriding methods.

For example see `Delegating*` classes in [package:collection](https://www.dartdocs.org/documentation/collection/1.14.3/collection/collection-library.html) and [package:async](https://www.dartdocs.org/documentation/async/1.13.3/async/async-library.html)

It would be cool if this was automatic rather than needing to manually write these classes.

Here's a straw man proposal:

```dart
abstract class SomeInterface {
String someMethod();
int someOtherMethod();
}

class Foo implements SomeInterface {
final delegate SomeInterface _delegate;
Foo(this._delegate);

@override
String someMethod() => 'Foo implementation';

// Implicitly:
// int someOtherMethod() => _delegate.someOtherMethod();
}
```

If:
- a field is marked `delegate`
- The delegate field is statically determined to be of type `Foo`
- The class `implements Foo`

Then:
- Any methods in `Foo` which are not directly implemented in the class are automatically implemented by forwarding to the field marked `delegate`.

I think this also could work with multiple delegates and it would be a static error to have a method with identical signatures in two interfaces with ambiguous forwarding. This is similar to a static error when implementing two interfaces with the same method and conflicting signatures.

```dart
class Foo implements First, Second {
final delegate First _first;
final delegate Second _second;
Foo(this._first, this._second);
}
```

Contributor guide

Open the contributing guide

Research direction

Start with the straw-man proposal and the linked Delegating* examples in package:collection and package:async. Determine the language-spec changes needed for single and multiple delegates, including ambiguous signatures and static errors. Done means an agreed design for method forwarding and its edge cases.

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.