language icon indicating copy to clipboard operation
language copied to clipboard

[Dot shorthands]: Allow shorthand syntax for instance methods in iterables

Open liamdoka opened this issue 2 months ago • 2 comments

This request focuses on Iterables and anonymous functions. Ideally, I'd like to be able to access an instance method on a parameter of an anonymous function with a known type.

Probably better described by an example:

class A {
  final bool b; // some member or getter.
}

final aList = <A>[A(), A(), A()];

// currently
final aPropertyList = aList.map((a) => a.b).

// ideal
final aPropertyList = aList.map(.b);

The proposal reduces noise around naming the lambda parameters in cases where they're not referenced again. Useful for when we don't "care" what the parameter is, because each one is transformed in the same way.


To incite further discussion, separate from the initial proposal, this may open the door to more complex evaluations which may be unintended.

Consider the following.


enum CompassPoint { north, south, east, west }

class Movement {
  final CompassPoint point;
  final int distance;
}

final movements = <Movement>[
  Movement(.north, 5),
  Movement(.east, 3),
  Movement(.north, 4),
];

// Current static proposal
final eastMovements = movements.where((movement) => movement.point case .east);

// Possible new syntax
final eastMovements = movements.where(.point == CompassPoint.east);

// or even more magical
/// in this scenario, the [case] keyword could limit the following context to enum members.
final northMovements = movements.where(.point case .north);

liamdoka avatar Oct 12 '25 01:10 liamdoka

I'd like to be able to access an instance method on a parameter of an anonymous function with a known type.

It can be ambiguous.

main() => where(E1.b == .b); // 'bool' can't be assigned to 'void Function(E2)'.

where(void Function(E2) f) => print(f.runtimeType);

enum E1 { a, b }
enum E2 { a, b }

Try in DartPad on the Main channel.

Wdestroier avatar Oct 12 '25 02:10 Wdestroier

This is more like #8 than dot-shorthands. It's omitting not just a target type, but a target object and a parameter taking that object.

Sounds similar to Ruby's static tear-off of instance members, which becomes a function taking an instance and invoking the instance member, so int.toRadixString(2) would become (int $tmp) => $tmp.toRadixString(2).

Just writing .toRadixString in a function context is probably a bit too far (even if it wasn't already ambiguous).

lrhn avatar Oct 12 '25 19:10 lrhn