Generics

Generics

List<E>
var names = List<String>(); 
names.addAll(['Seth', 'Kathy', 'Lars']); 

names.add(42); // Error
abstract class Cache<T> { 
   T getByKey(String key); 
   void setByKey(String key, T value); 
}
  • 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

var nameSet = Set<String>.from(names);
var views = Map<int, View>();

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

var names = List<String>(); 
names.addAll(['Seth', 'Kathy', 'Lars']); 
print(names is List<String>); // true

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.

Using generic methods

T first<T>(List<T> ts) { 
   // Do some initial work or error checking, then... 
   T tmp = ts[0]; 
   // Do some additional checking or processing... 
   return tmp; 
}

A newer syntax, called generic methods, allows type arguments on methods and functions.

Generics — Structure map

Clickable & Draggable!

Generics — Related pages: