dart-lang / language

Design of the Dart language
Other
2.66k stars 205 forks source link

Allow extension type to implement Record and Function types #3839

Open mmcdon20 opened 4 months ago

mmcdon20 commented 4 months ago

A common pattern in extension types is to implement the representation type. This even works if the representation type is a final class like String, but does not work for Function or Record types.

implements on a Record type should give you getters for each of its members. implements on a Function type should give you a call method.

extension type Coordinate(({double latitude, double longitude}) _) implements ({double latitude, double longitude}) {
  // gives you getters for .latitude and .longitude
}
extension type VoidFunction(void Function() _) implements void Function() {
  // gives you .call method
}
nate-thegrate commented 4 months ago

Only allowing implementation of named types was a deliberate choice—you can see an explanation at https://github.com/dart-lang/language/issues/3693#issuecomment-2039010173.

mmcdon20 commented 4 months ago

@nate-thegrate It sounds like it would be possible to allow this behavior, just that it hasn't been done yet due to being more complicated than named types to implement.

Also in some sense, the feature partially exists already in that you can cast the extension type to the representation type successfully.

extension type Coordinate(({double latitude, double longitude}) _) {}

void main() {
  Coordinate coordinate = Coordinate((latitude: 5, longitude: 10));

  ({double latitude, double longitude}) tuple =
      coordinate as ({double latitude, double longitude});

  print(tuple.latitude);
}

But it would be a lot more convenient to use if it did not require casting.

nate-thegrate commented 4 months ago

@mmcdon20 fair point!

I don't see this being implemented anytime soon, but I agree that it'd be really nice :)