dart-lang / dart-lang/language
Restrict public parameter to subtype of actual parameter.
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
If I want to have an optional parameter with a marker default value, but do not want the user to be able to pass that marker explicitly, then I'm not able to specify it in one method.
I can do an interface/implementation split:
```dart
abstract class Super {
factory Super() => _Sub();
void foo([int x]);
}
class _Sub implements Super {
void foo([int? x = null]) => .... x? ....;
}
```
A user only seeing the `Super` class will not be able to pass a `null` value to `foo`, but the implementation class has widened the type of the parameter to include a default value separate from the user-available arguments.
I would like to be able to do something like that for a *single* function: Specify one type for the caller visible signature, and a wider type for the local variable declared by the parameter, which is only visible inside the function. The default value can be of the wider type.
Maybe something like `int foo([int x as int? = null]) => ...x?....` would declare the local variable as `int? x` and the function signature as `int Function([int])`.
(Could also use that to *restrict* the type, so `(Object x as int) => ...` would provide a function signature of `... Function(Object)`, but check the argument with `as int` before assigning to the local variable `int x`. That's effectively a "covariant" function implementation, which has been requested before).
Contributor guide
Research direction
Start with the Super, _Sub, and foo examples in the issue, then compare the proposed `as` parameter syntax with Dart's existing function type and optional-parameter rules. Determine whether the requested caller-visible and local parameter types are specified consistently; done requires an accepted language-design decision and corresponding specification work.
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