dart-lang / dart-lang/language

Syntax sugar to generate instance method tear-offs without an instance as closures

Open
#2,349 4 comments 1 reaction 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 quite common to use a closure that takes a single parameter, and calls a single function on it.

For example, this pattern can be used to ensure that an API is only accessed in a safe manner:

```dart
class ApiService {
Future getData() { /* ... */ }
}
```

```dart
Future callApi(Future Function(ApiService apiService) action) async {
try {
return await action(_apiService);
} on ApiException {
// ...
};
}
```

```dart
final data = callApi((apiService) => apiService.getData());
```

It would be great to be able to create the `(apiService) => apiService.getData()` closure more concisely.

As static functions and instance functions cannot share names, the instance function could be automatically added as a static function, like so:

```dart
class MyClass {
void myInstanceFunction(Object a, Object b, Object c) {}
}

MyClass.myInstanceFunction; // (myObject, a, b, c) => myObject.myInstanceFunction(a, b, c);
```

That syntax may be a little confusing, though, as it adds a lot of duplicate functions - something like `MyClass.methods.myInstanceFunction` could be done instead.

Contributor guide

Open the contributing guide

Research direction

Start by reviewing the proposed closure pattern and the two syntax options in the issue. Determine the required semantics for instance-method tear-offs without an instance, including generic and argument behavior. Done means a settled language design with its syntax and behavior specified clearly enough for implementation.

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
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.