Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 61 ยท Practice and Review

Practice: Classes and Collections

Seven Dart exercises with solutions on classes, sealed hierarchies, generics, maps, grouping, value equality and enhanced enums, with runnable stand-ins.

The first practice lesson trained your fingers on variables, strings and control flow. This one moves to the middle of the language: writing your own types and shaping data with lists, sets and maps. The seven exercises mirror what you do in real Dart programs every day, such as modelling a shape, writing a small generic container, counting words, grouping records, and making two objects compare as equal.

As before, each exercise has a task, a hint and a collapsed solution written in real Dart (read-only on this site). Two TypeScript stand-ins run the same logic so you can compare the expected output with your own attempt. Try every exercise first, ideally in DartPad or with dart run, and only then open the solution.

flowchart TD
    A["Exercise 1<br/>class with a getter"] --> B["Exercise 2<br/>sealed hierarchy"]
    B --> C["Exercise 3<br/>generic Stack"]
    D["Exercise 4<br/>word counts in a Map"] --> E["Exercise 5<br/>grouping"]
    F["Exercise 6<br/>== and hashCode"] --> G["Exercise 7<br/>enhanced enum"]

Three themes: your own types (1 to 3), shaping collections (4 and 5), and identity and ordering (6 and 7).

Exercise 1: a Rectangle class

Task. Write a Rectangle class with two double fields, width and height. It needs a computed area, a computed isSquare, and a toString that prints Rectangle(3.0x4.0). Instances must be immutable.

Hint. Use a const constructor with initializing formals, final fields, and getters. See Constructors and Getters and Setters.

Show the solution
DART
class Rectangle {
  const Rectangle(this.width, this.height);

  final double width;
  final double height;

  double get area => width * height;
  bool get isSquare => width == height;

  @override
  String toString() => 'Rectangle(${width}x$height)';
}

void main() {
  const r = Rectangle(3, 4);        // 3 and 4 are int literals, accepted as doubles
  print(r);                          // Rectangle(3.0x4.0)
  print(r.area);                     // 12.0
  print(r.isSquare);                 // false
}

this.width in the constructor parameter list both declares the parameter and assigns the field. Getters look like fields to callers, but are calculated every time, so they can never go out of date.

Exercise 2: a sealed shape hierarchy

Task. Create a sealed class Shape with two subclasses, Circle(radius) and Square(side). Write double area(Shape shape) using a switch expression. Add up the areas of a list of shapes. The compiler must complain if someone later adds a Triangle and forgets to update area.

Hint. sealed makes the set of subtypes known, so a switch over it must be exhaustive. Object patterns such as Circle(:var radius) pull out fields (see Class Modifiers).

Show the solution
DART
import 'dart:math';

sealed class Shape {
  const Shape();
}

final class Circle extends Shape {
  const Circle(this.radius);
  final double radius;
}

final class Square extends Shape {
  const Square(this.side);
  final double side;
}

double area(Shape shape) => switch (shape) {
      Circle(:var radius) => pi * radius * radius,
      Square(:var side) => side * side,
    };

void main() {
  final shapes = [const Circle(1), const Square(2), const Square(3)];
  final total = shapes.fold<double>(0, (sum, s) => sum + area(s));
  print(total.toStringAsFixed(2));   // 16.14
}

There is no default case on purpose. With sealed, Dart knows Circle and Square are the only subtypes, and adding a third makes this switch a compile-time error until you handle it.

Exercise 3: a generic Stack

Task. Write Stack<T> with push, pop, a peek getter and isEmpty. pop on an empty stack must throw a StateError. peek must return null instead of throwing. Use it to check whether the brackets in "{[()]}" are balanced.

Hint. Keep a private List<T>. removeLast() and last do the work. The type of peek must admit null. See Generics.

Show the solution
DART
class Stack<T> {
  final List<T> _items = [];

  bool get isEmpty => _items.isEmpty;
  T? get peek => _items.isEmpty ? null : _items.last;

  void push(T item) => _items.add(item);

  T pop() {
    if (_items.isEmpty) throw StateError('Cannot pop an empty stack');
    return _items.removeLast();
  }
}

bool isBalanced(String text) {
  const pairs = {')': '(', ']': '[', '}': '{'};
  final open = Stack<String>();
  for (final ch in text.split('')) {
    if (pairs.containsValue(ch)) {
      open.push(ch);
    } else if (pairs.containsKey(ch)) {
      if (open.isEmpty || open.pop() != pairs[ch]) return false;
    }
  }
  return open.isEmpty;
}

The underscore makes _items private to the library, so callers cannot bypass the stack discipline. T? on peek is how Dart says "a T, or nothing".

Here is a stand-in for the first three exercises. TypeScript has no sealed classes, so a union type with a kind tag plays the same role: the never assignment fails to compile if a case is missing.

TypeScript Exercises 1 to 3 (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Exercise 4: count the words

Task. Write Map<String, int> countWords(String text). Ignore case and punctuation. Then print the three most frequent words, most frequent first, and break ties alphabetically. Test it with "the cat and the hat and the bat".

Hint. Split on anything that is not a letter with RegExp(r'[^a-z]+'). The map method update has an ifAbsent argument. To sort, convert counts.entries to a list (see Maps and Lists).

Show the solution
DART
Map<String, int> countWords(String text) {
  final counts = <String, int>{};
  for (final word in text.toLowerCase().split(RegExp(r'[^a-z]+'))) {
    if (word.isEmpty) continue;
    counts.update(word, (n) => n + 1, ifAbsent: () => 1);
  }
  return counts;
}

void main() {
  final counts = countWords('the cat and the hat and the bat');
  final ranked = counts.entries.toList()
    ..sort((a, b) {
      final byCount = b.value.compareTo(a.value);          // larger first
      return byCount != 0 ? byCount : a.key.compareTo(b.key);
    });
  for (final e in ranked.take(3)) {
    print('${e.key}: ${e.value}');
  }
  // the: 3, and: 2, bat: 1
}

split can produce empty strings at the edges, hence the isEmpty guard. The cascade ..sort(...) sorts the list in place and still returns the list. The comparator returns a negative, zero or positive number, and the tie-break only runs when the counts are equal.

Exercise 5: group items by a key

Task. Write a generic Map<K, List<V>> groupBy<K, V>(Iterable<V> items, K Function(V) key). Use it to group the names ['Ada', 'Alan', 'Grace', 'Linus', 'Guido'] by first letter.

Hint. putIfAbsent(key, () => []) returns the existing list or creates a new one, and you can call .add straight on the result.

Show the solution
DART
Map<K, List<V>> groupBy<K, V>(Iterable<V> items, K Function(V) key) {
  final groups = <K, List<V>>{};
  for (final item in items) {
    groups.putIfAbsent(key(item), () => []).add(item);
  }
  return groups;
}

void main() {
  final names = ['Ada', 'Alan', 'Grace', 'Linus', 'Guido'];
  print(groupBy(names, (n) => n[0]));
  // {A: [Ada, Alan], G: [Grace, Guido], L: [Linus]}
}

The function takes another function as an argument, so the grouping rule is chosen by the caller (see First-Class Functions). Dart infers K as String from the lambda. Maps keep insertion order, which is why A comes before G.

Exercise 6: value equality

Task. A Point has integer x and y. Two points with the same coordinates must be equal, and adding both to a Set must keep only one. Override == and hashCode.

Hint. Object.hash(x, y) combines fields into one hash code. The rule is: if a == b, then a.hashCode == b.hashCode (see Operator Overloading).

Show the solution
DART
class Point {
  const Point(this.x, this.y);
  final int x;
  final int y;

  @override
  bool operator ==(Object other) =>
      other is Point && other.x == x && other.y == y;

  @override
  int get hashCode => Object.hash(x, y);

  @override
  String toString() => '($x, $y)';
}

void main() {
  final points = {const Point(1, 2), const Point(1, 2), const Point(3, 4)};
  print(points.length);   // 2
}

Without the overrides, every Point is only equal to itself, and the set would hold three entries. A record such as (1, 2) already has structural equality and a matching hash code, which is why records are often the simpler choice for small values.

Exercise 7: an enhanced enum

Task. Create an enum Priority with low, medium and high. Each value has a numeric weight (1, 2, 3) and a text label. Sort a list of (title, priority) pairs with the highest priority first and ties in alphabetical order.

Hint. Enhanced enums can have fields and a const constructor. values lists every constant (see Enums).

Show the solution
DART
enum Priority {
  low(1, 'Low'),
  medium(2, 'Medium'),
  high(3, 'High');

  const Priority(this.weight, this.label);
  final int weight;
  final String label;
}

void main() {
  final tasks = [
    ('write tests', Priority.medium),
    ('fix bug', Priority.high),
    ('deploy', Priority.high),
    ('tidy docs', Priority.low),
  ];
  tasks.sort((a, b) {
    final byPriority = b.$2.weight.compareTo(a.$2.weight);
    return byPriority != 0 ? byPriority : a.$1.compareTo(b.$1);
  });
  for (final (title, priority) in tasks) {
    print('${priority.label.padRight(6)} $title');
  }
}

Record fields are read with $1 and $2, and the for (final (title, priority) in tasks) loop destructures each record right in the loop header. Storing weight in the enum avoids relying on index, which would silently change if someone reordered the constants.

The second stand-in runs exercises 4 to 7 side by side. Predict each line of output before you press the button.

TypeScript Exercises 4 to 7 (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Going further

  • Add a Triangle to exercise 2 and watch the compiler point at every switch that needs updating.
  • Give Stack<T> a toString and an Iterable<T> view (hint: List.unmodifiable).
  • Change countWords so it takes a set of stop words to ignore.
  • Make Point implement Comparable<Point> so a list of points can be sorted with sort() and no argument.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does exercise 2 have no default branch in its switch?

    A sealed class has a closed set of direct subtypes, so Dart can verify every case is handled. A default branch would hide a forgotten new subtype.
  2. 2. What does groups.putIfAbsent(key, () => []).add(item) do when the key is new?

    putIfAbsent runs the callback only for a missing key, stores the result and returns the list stored under the key, either way.
  3. 3. If you override == in a class, what else should you override?

    Equal objects must have equal hash codes, otherwise hash-based collections such as Set and Map misbehave.
  4. 4. Why is Stack.peek declared as T??

    An empty stack has no top element, and T? lets the getter report that honestly instead of throwing.

Summary

  • Use const constructors, final fields and getters to build small immutable classes.
  • A sealed class plus a switch expression gives compiler-checked, exhaustive logic over a family of types.
  • Generic classes such as Stack<T> reuse one implementation for any element type; T? models "maybe nothing".
  • update, putIfAbsent and entries are the everyday Map tools for counting and grouping.
  • Override == and hashCode together, or use records, to get value equality.
  • Enhanced enums can carry data, which is safer than relying on their index.

Continue with Practice: Async and Streams.