Restricting the parameterized type

When implementing a generic type,you might want to limit the types of its parameters.You can do this using extends.

  1. class Foo<T extends SomeBaseClass> {
  2. // Implementation goes here...
  3. String toString() => "Instance of 'Foo<$T>'";
  4. }
  5.  
  6. class Extender extends SomeBaseClass {...}

It’s OK to use SomeBaseClass or any of its subclasses as generic argument:

  1. var someBaseClassFoo = Foo<SomeBaseClass>();
  2. var extenderFoo = Foo<Extender>();

It’s also OK to specify no generic argument:

  1. var foo = Foo();
  2. print(foo); // Instance of 'Foo<SomeBaseClass>'

Specifying any non-SomeBaseClass type results in an error:

  1. var foo = Foo<Object>();