dart-lang / language

Design of the Dart language
Other
2.65k stars 201 forks source link

Pattern-esque syntax for terser named arguments/record fields #3102

Open nex3 opened 1 year ago

nex3 commented 1 year ago

The pattern-matching syntax introduces the constructs :var foo and :foo to declare a variable whose name matches a field on the object being matched. The purpose of this is to reduce duplication, to users don't have to explicitly write foo: var foo.

I propose using this syntax as a way to reduce duplication when passing named arguments (or constructing records). Specifically, make foo(:argument) equivalent to foo(argument: argument). Similarly, record literals could be declared using (:field) instead of (field: field). This would help reduce duplication and ease acclimation to Dart for users coming from JS, which supports similar behavior when using maps as named arguments (in JS, foo({argument}) is equivalent to foo({argument: argument})).

lrhn commented 1 year ago

It's definitely going to be briefer, and is likely to get used a lot.

We'd have to define which expressions counts as having a "name" that can be used as parameter/field name.

Those are fairly safe. Then there are the more speculative ones:

nex3 commented 1 year ago

The analogous feature in JS only works for plain identifiers, but it would be pretty neat to be able to use at least expressions ending in .identifier. Most of the others seem confusingly weird to me.

munificent commented 1 year ago

I really like this idea. As @nex3 suggests, I'd probably want to stick to simple identifiers and maybe identifiers wrapped in prefix expressions (which we allow for patterns). Going beyond that gets weird fast.

DerpMcDerp commented 4 months ago

Terse bools would be nice too:

(+:foo, -:bar) => (foo: true, bar: false)