Generics
Generics
- You can use generics to reduce code duplication.
- Properly specifying generic types results in better generated code.
- Generics are often required for type safety.
Using collection literals
var names = <String>['Seth', 'Kathy', 'Lars'];
var uniqueNames = <String>{'Seth', 'Kathy', 'Lars'};
var pages = <String, String>{
'index.html': 'Homepage',
'robots.txt': 'Hints for web robots',
'humans.txt': 'We are people, not machines'
};
Parameterized literals are just like the literals you’ve already seen, except that you add <type> (for lists and sets) or <keyType, valueType> (for maps) before the opening bracket. Here is an example of using typed literals.
Using parameterized types with constructors
To specify one or more types when using a constructor, put the types in angle brackets (<...>) just after the class name.
Generic collections and the types they contain
Restricting the parameterized type
class Foo<T extends SomeBaseClass> {
// Implementation goes here...
String toString() => "Instance of 'Foo<$T>'";
}
class Extender extends SomeBaseClass {...}
When implementing a generic type, you might want to limit the types of its parameters. You can do this using extends.