CodeBlanks Logo Icon CodeBlanks

Type constraints

Learn type constraints with extends.

Type constraints (extends)

Sometimes T must not be any type but only a specific subset. For this the type parameter gets an upper bound with extends: <T extends num>.

Example: T max<T extends num>(T a, T b) { return a > b ? a : b; }. Here T can only be a subtype of num; that is int or double. The > comparison is defined on num, so it compiles. Without the constraint T could be anything and > would not be available. A constraint gives generic code a strong contract.

Why constrain?

Without a constraint T covers all types; but that means you can only call Object methods on T. Operators like +, -, > raise a compile error.

When you write <T extends num>, Dart knows T carries num behavior; +, -, > and compareTo become available. This is how mathematical helper methods are written generically and type-safely. For example average, max and min methods work for every number type with a single T extends num definition.

Practice Write a max<T extends num> method

Define a constrained generic method named T max<T extends num>(T a, T b); its body should be return a > b ? a : b;. In main, call print(max<int>(3, 7));.

Starter code

main.dart
// Define the max<T extends num> method

void main() {
  // Call max<int>(3, 7) and print
}

Sample solution

main.dart
// Define the max<T extends num> method
T max<T extends num>(T a, T b) {
  return a > b ? a : b;
}

void main() {
  print(max<int>(3, 7));
}

Expected output

7

Questions and answers

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

1 Match the constraint parts

Term Meaning
extends Constraint keyword
T Type parameter
num Upper bound

2 What does the <T extends num> constraint provide?

  • T can only be String
  • T can only be bool
  • T can be any type
  • T can only be num (int or double) Correct answer

Explanation: extends num limits T to int and double.

3 Add a constraint to max

Question
T max<T ____>(T a, T b) {
  return a > b ? a : b;
}
Answer
T max<T extends num>(T a, T b) {
  return a > b ? a : b;
}

Explanation: The <T extends num> constraint limits max to numbers.

All lessons in Intermediate