Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an instance of a generic type in DART

Tags:

dart

I was wondering if is possible to create an instance of a generic type in Dart. In other languages like Java you could work around this using reflection, but I'm not sure if this is possible in Dart.

I have this class:

class GenericController <T extends RequestHandler> {      void processRequest() {         T t = new T();  // ERROR     } } 
like image 374
shuriquen Avatar asked Apr 16 '14 14:04

shuriquen


People also ask

Can generic class instance be created?

Yes, this is nice especially if the generic class is abstract, you can do this in the concrete subclasses :) @TimKuipers The <E> in class Foo<E> is not bound to any particular type.

What is generic type in Dart?

Dart Generics are the same as the Dart collections, which are used to store the homogenous data. As we discussed in the Dart features, it is an optionally typed language. By default, Dart Collections are the heterogeneous type. In other words, a single Dart collection can hold the values of several data types.


1 Answers

I tried mezonis approach with the Activator and it works. But it is an expensive approach as it uses mirrors, which requires you to use "mirrorsUsed" if you don't want to have a 2-4MB js file.

This morning I had the idea to use a generic typedef as generator and thus get rid of reflection:

You define a method type like this: (Add params if necessary)

typedef S ItemCreator<S>(); 

or even better:

typedef ItemCreator<S> = S Function(); 

Then in the class that needs to create the new instances:

class PagedListData<T>{   ...   ItemCreator<T> creator;   PagedListData(ItemCreator<T> this.creator) {    }    void performMagic() {       T item = creator();       ...    } } 

Then you can instantiate the PagedList like this:

PagedListData<UserListItem> users           = new PagedListData<UserListItem>(()=> new UserListItem()); 

You don't lose the advantage of using generic because at declaration time you need to provide the target class anyway, so defining the creator method doesn't hurt.

like image 137
Patrick Cornelissen Avatar answered Oct 02 '22 18:10

Patrick Cornelissen