Re: [dart-misc] What's possible with Dart Generics at runtime in Flutter

50 views
Skip to first unread message

Bob Nystrom

unread,
Apr 16, 2018, 12:43:18 PM4/16/18
to General Dart Discussion


On Wed, Apr 11, 2018 at 9:20 AM, mythz <demis....@gmail.com> wrote:
I'm developing a serialization library that works in flutter so I'm avoiding Mirrors and would like to know what's possible with runtime generics in Dart/flutter to find out what needs to be code-gen'ed and what can be automated with generic routines. 

Firstly how can we can get the runtime time of a generic argument?

T create<T>() {
   var runtimeTypeOfT = ... ?
}

"T":

T create<T>() {
   var runtimeTypeOfT = T;
}


Is it possible to create a new instance of T where T has an empty constructor, e.g:

T create<T>() {
    var instance = new T();
    return instance;
}

This is possible in C# without reflection by using the `where T : new()` type constraint, how can we do this in Dart/Flutter?

No, there's no way to do this in Dart currently without using some sort of code generation approach.
 
Can we create a generic factory function which creates a generic list with the runtime argType? 

List createList(String argType) {
   var newGenericList = ... // create List<argType>?
   return newGenericList;
}

So that we can could use it to create generic lists like:

List<int> intList = createList("int");
List<String> stringList = createList("String");

No, there's no way to do this either. Supporting something like this in general would make it very hard to do tree shaking, which is vital for controlling code size on the web.
 
As a current workaround/hack I'm generating a dictionary of factory constructors like:

{
  'List<String>': () => new List<String>(),
  'Map<String,int>': () => new Map<String,int>(),
}

This is, I think, the best current solution. It's not ideal, but metaprogramming is generally pretty hard in a language that is compiled ahead of time and where users also care deeply about generated code size. Dart 2 is more like C++ than, say, C# where you can rely on a VM and a JIT and where generated code size isn't usually a big concern.

I hope that eventually we can add some more powerful static metaprogramming features to Dart, but it's a really challenging problem and there are few successful languages out there in the same space that we can learn from.

Cheers!

– bob

Reply all
Reply to author
Forward
0 new messages