Search code examples
darttypessubclassing

How to specify a data type for a container class in Dart


I am looking for the dart syntax to achieve the following but do not know what the correct terminology is to search for the answer.

class BaseClass <T extends MyType> {

  List<T> items;

  T getFirstItem() => items.first;
}

and then be able to Sub class like this

class ClassForMyType<MyType> extends BaseClass {
   List<MyType> items;

   MyType getFirstItem() => items.first;
}

Where ClassForMyType would extend BaseClass so that I do not have to re-implement the contrived getFirstItem() method.

Effectively I want to be able to use it like this:

ClassForMyType container = ClassForMyType();
MyType item = Mytype();
container.items.add(item);
List<MyType> itemsFromContainer = container.items;
MyType firstItem = container.getFirstItem();

I have tried something like this:


BaseClass<T extends MyType> {
  List<T> items;
  void addItemFromMap(Map map) {
    items.add(T.fromMap(map));
  }
}

The above fails on the .fromMap() which does exist on MyType. In other methods where I access other methods on MyType these appear to work, it seems to have a problem only wiht the named contructor.


Solution

  • I think the only way that would work and look relatively OK would be:

    
    abstract class BaseClass<T extends MyType> {
      List<T> items;
    
      // abstract factory method
      T itemFromMap(Map map);
      
      void addItemFromMap(Map map) {
        items.add(itemFromMap(map));
      }
    
    }
    
    class ClassForMyType extends BaseClass<MyType> {
      
      // implementing abstract factory method, delegating call to constructor
      MyType itemFromMap(Map map) => MyType.fromMap(map);
    
    }
    
    

    I agree, a little bit overhead that you should implement factory method in every subclass, but that is the only proper way.