Junior — Middle
How is support for generic types implemented in Dart language?
sobes.tech AI
Answer from AI
In Dart language, support for generics is implemented through parameterization of classes, methods, and functions with types. This allows creating universal components that work with different data types while maintaining type safety.
Generics in Dart are specified using angle brackets <T>, where T is a type parameter.
Example of a generic class:
class Box<T> {
T value;
Box(this.value);
void updateValue(T newValue) {
value = newValue;
}
}
void main() {
var intBox = Box<int>(123);
var strBox = Box<String>("hello");
intBox.updateValue(456);
strBox.updateValue("world");
}
Dart supports type parameter bounds, for example:
class NumberBox<T extends num> {
T value;
NumberBox(this.value);
}
Thus, generics in Dart are implemented at the language level with support for parameterization and bounds, enabling the writing of flexible and type-safe code.