Generic class
- Dart course
- Intermediate
- Lesson 30/116
- 5 min
Learn generic classes with <T>.
What is a generic class?
A generic class is a class that takes a type parameter. The type parameter is written inside angle brackets: <T>. T is a placeholder; it is replaced by a real type when the class is used.
Example: class Box<T> { T value; Box(this.value); }. Here Box works with any type: Box<int>, Box<String>. The type parameter makes a single class definition reusable for many types. Compile-time type safety is enforced; assigning the wrong type is a compile error.
The Box<T> example
To use Box<T> with a concrete type, write the type argument explicitly: var b = Box<int>(42);. Now b.value is an int.
Dart often infers the type: writing var b = Box(42); lets Dart figure out that T is int. But explicit typing improves readability. You do not need to redefine the class for each type; a single Box<T> definition works for numbers, text and custom types. This is the core power of generic classes.
Practice Define and use a Box<T> class
Define a generic class named Box<T>. Give it a T value field and a Box(this.value) constructor. In main, create an instance with var b = Box<int>(42); and call print(b.value).
Starter code
// Define the Box<T> class
// Create a Box<int> instance in main
void main() {
// print b.value
}Sample solution
// Define the Box<T> class
class Box<T> {
T value;
Box(this.value);
}
void main() {
var b = Box<int>(42);
print(b.value);
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why use a generic class?
- To shrink the memory footprint of a class
- To combine type safety and reuse in one definition Correct answer
- To hide constructors
- To speed up runtime
Explanation: A generic class uses one definition for many types without losing type safety.
2 Add the type parameter to Box
class Box____ {
T value;
Box(this.value);
}
class Box<T> {
T value;
Box(this.value);
}
Explanation: The <T> type parameter makes Box generic.
3 Match the Box<T> parts
| Term | Meaning |
|---|---|
Box |
Class name |
T |
Type parameter |
value |
Field name |