Description
Optional positional parameters coexisting with named parameters would be great by any means, and we already have some well-thought-out feature proposals:
- Allow both optional positional and optional named arguments in the same function signature. #1076
- Simplified parameters, nullable means optional #2232
This issue presents a slight variation on those ideas.
Maybe the compiler could "automatically add the square brackets" to as many parameters as it can, starting from the rightmost positional parameter. For example:
foo(int a, int? b) {
// b is optional
}
foo(int? a, int b) {
// both parameters are required
}
foo(int a = 42, int? b) {
// both parameters are optional
}
foo(int? a = 42) {
// should probably trigger a linter warning, since "?" signals that the param is null by default
}
foo(int a = 42, int b) {
// compile-time error
}
That compile-time error would be consistent with e.g. Python:
def foo(a=42, b):
return a + b
File "script.py", line 1
def foo(a=42, b):
^
SyntaxError: parameter without a default follows parameter with a default
If this were implemented, named arguments could follow a similar pattern: instead of typing required
, a named argument would be required if it's non-nullable and lacks a default value. (A nullable parameter such as a button's onPressed could be given a @required
annotation if desired.)
Essentially, this is identical to the proposal in #2232 but would also allow for parameters with default values, since I think it's really cool that the IDE shows this info when your mouse is hovering on a constructor.