Bỏ qua để đến nội dung

Generics

🎯 Mục tiêu: Type-safe code với generics.


class Box<T> {
T value;
Box(this.value);
}
var intBox = Box<int>(42);
var stringBox = Box<String>("Hello");

T first<T>(List<T> items) => items.first;
var number = first<int>([1, 2, 3]); // Type inference
var word = first(['a', 'b', 'c']);

class SortedList<T extends Comparable<T>> {
final List<T> _items = [];
void add(T item) {
_items.add(item);
_items.sort();
}
}

  • <T> cho type parameter
  • extends cho constraints
  • Collections là generic: List<T>, Map<K, V>