
上QQ阅读APP看书,第一时间看更新
When and why to use generics
The use of generics can help a developer to maintain and keep collection behavior under control. When we use a collection without specifying the allowed element types, it is our responsibility to correctly insert the elements. This, in a wider context, can become expensive, as we need to implement validations to prevent wrong insertions and to document it for a team.
Consider the following code example; as we have named the variable avengerNames, we expect it to be a list of names and nothing else. Unfortunately, in the coded form, we can also insert a number into the list, causing disorganization or confusion:
main() {
List avengerNames = ["Hulk", "Captain America"];
avengerNames.add(1);
print("Avenger names: $avengerNames");
// prints Avenger names: [Hulk, Captain America, 1]
}
However, if we specify the string type for the list, then this code would not compile, avoiding this confusion:
main() {
List<String> avengerNames = ["Hulk", "Captain America"];
avengerNames.add(1);
// Now, add() function expects an 'int' so this doesn't compile
print("Avenger names: $avengerNames");
}