CodeBlanks Logo Icon CodeBlanks

Summary - Type aliases

Combine typedef, Record and pattern matching to write a DTO system.

Summary: Type aliases

In this group you named function types with typedef and complex types with a type alias. You bundled values with a Record, unpacked them with pattern matching and produced results by pattern with a switch expression.

Now we combine them: we will name a Record with a type alias and match it with a switch expression. This shows Dart 3's data power.

Remember: an alias only names, a Record is immutable and a switch expression produces a value.

Practice The Point DTO

Define typedef Point = (int x, int y);. In main create Point p = (3, 4);. Match p with a switch expression: (0, _) => 'on axis', (_, 0) => 'on axis', _ => 'in plane'. Print the result with print.

Starter code

main.dart
// Create a record using the Point alias

void main() {
  // create a Point from (3, 4)
  // print the result of a switch expression
}

Sample solution

main.dart
typedef Point = (int x, int y);

void main() {
  Point p = (3, 4);
  print(switch (p) {
    (0, _) => 'on axis',
    (_, 0) => 'on axis',
    _ => 'in plane',
  });
}

Expected output

in plane

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Concept matching

Term Meaning
typedef Names a function type
type alias Names a complex type
Record Value bundle
switch expression Result by pattern

2 Result for Point p = (3,4)?

  • on axis
  • Empty
  • Error
  • in plane Correct answer

Explanation: (3,4) is not on an axis so the _ arm runs.

3 Record wildcard pattern

Question
switch (p) {
  (0, ____) => 'eksende',
  _ => 'düzlemde',
}
Answer
switch (p) {
  (0, _) => 'eksende',
  _ => 'düzlemde',
}

Explanation: To ignore a field write _.

All lessons in Intermediate