Skip to content

Record "construction" syntax for typedef #2528

Closed
@srawlins

Description

@srawlins

Don't you hate it when you are excited to use Records and try them out:

List<({int height, int width})> gatherPoints() {
  var first = (height: 1, width: 2);
  var second = (heighth: 3, width: 4);
  var more = [
    (height: 5, width: 6),
    (hieght: 7, width: 8),
  ];
  return [first, second, ...more];
}

And you're greeted (theoretically) with a static error that a List<Record> is returned, but a List<({int height, int width})> was expected! Where did you go wrong? What do you change? What a mess!

You may be quick to see my errors here, but imagine a more complicated example, maybe more lines, more inference, type promotion, return values, lots of var this and final that. Perhaps you have just recently changed the name of one field in the record type in the return type, and you're working on cleaning up the record literals.

There has to be a better way!

What if we introduced a record "construction" syntax with a typedef, similar to said support for interface types:

typedef MyList = List<int>;

var x = MyList.of([1,2,3]); // Ooooooh, love!

typedef Rectangle = ({int height, int width});

List<Rectangle> gatherPoints() {
  var first = Rectangle(height: 1, width: 2);
  var second = Rectangle(heighth: 3, width: 4); // 1
  var more = [
    Rectangle(height: 5, width: 6),
    Rectangle(hieght: 7, width: 8), // 2
  ];
  return [first, second, ...more];
}

Ah ha, now I get static errors at // 1 and at // 2, pointing out my spelling mistakes.

I know that my Ron Popeil pitch has persuaded you :). You won't regret it!

Yes I only got the benefit of matching a Rectangle's fields with those in the literals because I took the time to spell out Rectangle, begrudgingly forced to program with characters in the main stretch of the keyboard, but such a small price. And Yes this could be similarly solved by requiring types everywhere (like Rectangle second = Rectangle(heighth: 3, width: 4); or var more = <Rectangle>[), but, no thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problemsrecordsIssues related to records.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions