dart-lang / dart-lang/language

Enhancing Flexibility in Method Overrides

Open
#4,138 1 comment 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

Dart's strict method signature matching for overrides limits subclasses from using meaningful parameter names. This impacts methods clarity and usability, leading to unnecessary boilerplate.

```dart
// Bass class
class Pair {
final T first;
final U second;

Pair(this.first, this.second);

Pair copyWith({T? first, U? second}) => Pair(
first ?? this.first,
second ?? this.second,
);
}

//Subclass
class Range extends Pair {
Range({T? lower, T? upper}) : super(lower, upper);

T? get lower => first;
T? get upper => second;

// Overriding copyWith without signature mismatch, but losing clarity.
@override
Range copyWith({T? first, T? second}) => Range(
lower: first ?? this.lower,
upper: second ?? this.upper,
);

// A separate copyWithRange method that is redundant and inefficient
Range copyWithRange({T? lower, T? upper}) => Range(
lower: lower ?? this.lower,
upper: upper ?? this.upper,
);

// Ideal, but causes signature mismatch error
@override
Range copyWith({T? lower, T? upper}) => Range(
lower: lower ?? this.lower,
upper: upper ?? this.upper,
);
}
```

In this example, the subclass `Range` ideally wants to use parameters like `lower` and `upper` to represent the bounds of the range, but is forced to stick with `first` and `second` to avoid signature mismatches. Introducing another method like `copyWithRange` becomes redundant and inefficient.

### Solution Proposal:
Dart should allow parameter renaming in method overrides, maintaining type compatibility with the base class. This would enhance clarity without breaking contracts.

**Possible Syntax:**
```dart
Range copyWith({
T? lower as first,
T? upper as second
}) => Range(
lower: lower ?? this.lower,
upper: upper ?? this.upper,
);
```
In this solution, the `lower` and `upper` parameters are mapped to the base class's `first` and `second`, allowing more meaningful parameter names in the subclass without breaking the base class contract.

Contributor guide

Open the contributing guide

Research direction

Start with the Pair and Range example in the issue and review Dart's existing method-override rules for named parameters. Compare the proposed `lower as first` and `upper as second` syntax against type compatibility and base-class callers; done means the language-design tradeoffs and required behavior are documented or decided.

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
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.