Dart Generics
Generics allow you to write code without specifying a concrete type, using type parameters as placeholders, and determine the type when used.
The core value of generics is type safety and code reuseβone piece of code adapts to multiple types, while the compiler helps you check for type errors.
* * *
## Why Generics Are Needed
Let's first look at the pain points without generics.
## Example
Without generics:
// Without generics: can only store Object, need manual casting when retrieving
class IntBox {
int value;
IntBox(this.value);
}
class StringBox {
String value;
StringBox(this.value);
}
// For each new type, you need to write a new Box class, resulting in a lot of code duplication
void main(){
var intBox = IntBox(42);
var stringBox = StringBox('TUTORIAL');
print('Integer: ${intBox.value}');
print('String: ${stringBox.value}');
}
Is there a way to write a Box class that can hold both int and String, while ensuring type safety at compile time?
This is the problem that generics solve.
* * *
## Generic Classes
Generic classes declare type parameters using angle brackets <> after the class name, and use this type parameter inside the class.
## Example
// is a type parameter, T is a placeholder representing "some type"
// Conventional naming: T (Type), E (Element), K (Key), V (Value)
class Box{
T value;
Box(this.value);
T getValue(){
return value;
}
void setValue(T newValue){
value = newValue;
}
void printValue(){
print('Value in Box: $value (type: ${value.runtimeType})');
}
}
void main(){
// Specify concrete type when using generic class
var intBox = Box(42);
var stringBox = Box('TUTORIAL Dart Tutorial');
var doubleBox = Box(3.14);
intBox.printValue();
stringBox.printValue();
double
YouTip