dart-lang / dart-lang/language
Provide better support for default function parameters
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
I looked through some other issues, but (to my surprise) did not find what I am looking for.
TL;DR: I am looking for syntax like the following:
```dart
void fn({
// default here is a common super type for optional function parameters
T optionalValue = default,
}) {
if (optionalValue == default) { // or maybe "is default"
// ...
}
}
```
Nullable default parameters work great until you have a type `T` that is nullable that you need to pass into a function.
Dart has no support for such a situation.
There are two workarounds (at least that I am aware of), both of which have some problems.
1. Create a private const default parameter object, and then use an abstract method to override the parameter type:
```dart
class _DefaultParameter {
const _DefaultParameter();
}
const _defaultParam = _DefaultParameter();
abstract class A {
void fn({T myValue});
}
@internal
class B extends A {
void fn({Object? myValue = _defaultParam}) {
if (myValue is T) {
// myValue was explicitly set
} else {
// myValue is default
}
}
}
```
But this forces you into inheritance and some really ugly generic work. What happens if you just need a function? Perhaps you can use a callable class, or a function typedef, but both of those require another workaround too.
2. Use an `Option` or similar class from functional programming.
```dart
void fn({Option myValue = None()}) {
if (myValue case Some(:data)) {
// use data.
}
}
```
However, this requires users to explicitly wrap the parameter in `Some(myValue)`, and requires a dependency on some `Option` implementation.
Each of these workarounds has drawbacks.
Any sort of `copyWith` method (amongst many others) run into this issue when handling nullable members, and is forced to implement one of the above.
Perhaps this proposed default super type would act similar to null, with a builtin type union?
Contributor guide
Research direction
Start with the proposed syntax and the nullable generic-parameter examples in this issue, then read the six-comment discussion for constraints and prior decisions. Done means a settled language specification or design for detecting an omitted argument without the listed workarounds; the issue names no files or tests.
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