๐ŸŽ“ A1Learner
๐Ÿ”
0 of 24 lessons completed

Dart Records in Functions

A function can return a record when one result needs several values. A record type alias gives that record shape a short name for signatures.

Returning the lowest and highest values

minMax scans the list once and returns both ends in one record. The call site unpacks the record into low and high.

(int, int) minMax(List<int> nums) {
  var low = nums[0];
  var high = nums[0];
  for (var n in nums) {
    if (n < low) {
      low = n;
    }
    if (n > high) {
      high = n;
    }
  }
  return (low, high);
}

void main() {
  var (low, high) = minMax([4, 9, 2, 7]);
  print('low $low high $high');
}

A record type alias in signatures

Pair stands for the record type (int, String). labelNumber returns a Pair and showPair takes a Pair as its parameter.

typedef Pair = (int, String);

Pair labelNumber(int n, String word) {
  return (n, word);
}

String showPair(Pair pair) {
  return '${pair.$1}: ${pair.$2}';
}

void main() {
  Pair pair = labelNumber(3, 'three');
  print(showPair(pair));
  print(showPair((4, 'four')));
}

Taking a named-field record

locate takes one record with named fields x and y. The body reads the fields by name to build its text.

String locate(({int x, int y}) point) {
  return 'x is ${point.x}, y is ${point.y}';
}

void main() {
  print(locate((x: 2, y: 5)));
  print(locate((x: 0, y: 1)));
}

Example

({int count, int total}) summarise(List<int> scores) {
  var total = 0;
  for (var score in scores) {
    total = total + score;
  }
  return (count: scores.length, total: total);
}

void main() {
  var summary = summarise([10, 20, 30]);
  print('count ${summary.count}');
  print('total ${summary.total}');
}

Key points

  • A record return type packs several results into one return value.
  • The caller can unpack the returned record with destructuring at the call site.
  • A typedef gives a record type a name, so a long record type can appear in signatures as one word.
  • An aliased record type works as both a parameter type and a return type.
  • A function can take a named-field record and read the fields by name inside its body.

In this example, summarise adds the three scores and returns a record with named fields count and total. The first print reads the count field and shows 3. The second print reads the total field and shows 60.

Note

A typedef names a type only. It does not create a value.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does typedef Pair = (int, String); do?