FPGA
FPGA

Reputation: 3855

Why can't i use Type variable as a Type parameter to a generic class

class Cage<T>{
  Cage();
}

class Chicken{
  Chicken();
}

main() {
  Type t= Chicken;
  var cage = new Cage<t>();        //Does not work
  var cage2 = new Cage<Chicken>(); //Works
}

Why cant I use Type variable as a Type parameter to a generic class?

here is a part of my problem, easy to solve by sending the type variable to the constructor but makes it ugly

class Injector{
  Map<Symbol, DependencyMapping> _dependencyMappings;

  //problem comes here
  RegisterDependency(Type type,[Symbol name=#unnamed]){
     //...
     var mapping = new DependencyMapping<type>(name);
  } 

}

class DependencyMapping<T>{
  //...
}

abstract class DependencyProvider<T> {
  //...
}

class ValueProvider<T> implements DependencyProvider {
  //...
}

class ClassProvider<T> implements DependencyProvider {
  //...
}

class SingletonProvider<T> implements DependencyProvider {
  //...
}

Upvotes: 11

Views: 2026

Answers (2)

Gilad Bracha
Gilad Bracha

Reputation: 211

This is not possible in Dart as it stands today.

Parameterized types (things like List<int>) can take literal types (e.g., List<Chicken>) or type parameters (e.g., List<T> where T is declared as a type parameter in a generic, as it in Cage) as arguments. They cannot take arbitrary expressions, even if those are of type Type.

A variable such as t might hold a Type (as in your example) but in general it is really hard to be sure of that. It could just as easily hold a non-type value such as the number 3, because Dart's type system does not guarantee that something with static type Type really is a Type.

If we let these through, the system would be thoroughly corrupted. We could add runtime checks for that, but that would hit performance.

Upvotes: 10

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657148

This is not (yet) supported.

There was some explanation somewhere, I'll have to look it up....

Upvotes: 1

Related Questions