Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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 {
  //...
}
like image 690
FPGA Avatar asked Jan 21 '15 05:01

FPGA


People also ask

How many type parameters can be used in a generic class?

Multiple parameters You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.


1 Answers

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.

like image 77
Gilad Bracha Avatar answered Nov 15 '22 20:11

Gilad Bracha