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 {
//...
}
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.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With