How do you pass a list of types (NOT a list of instances!) to a method? And how do you compare if an instance matches any of the types from the list?
For example: This pseudo code wants to do something if someInstance
is of a type that matches any of the types in typesOfInterest
.
void doSomethingWithSpecificTypesOnly<T>(List<T> typesOfInterest) {
Object someInstance;
for (T thisType in typesOfInterest) {
if (someInstance is thisType) {
// do something...
}
}
}
Problem is, I can't figure out the syntax, so your help is very much appreciated. Thank you.
CodePudding user response:
I recommend creating a representation of a "type" with the operations that you need. (The Type
class is very likely not that, since it has no operations other than equality.)
Something like:
class MyType<T> {
bool isInstance(Object? object) => object is T;
bool operator >=(MyType other) => other is MyType<T>;
bool operator <=(MyType other) => other >= this;
R runWith<R>(R Function<X>() function) => function<T>();
}
void doSomethingWithSpecificTypesOnly<T>(List<MyType<T>> typesOfInterest) {
Object someInstance;
for (T thisType in typesOfInterest) {
if (thisType.isInstance(someInstance)) {
// do something...
}
}
}
By keeping the type as a type parameter, it stays accessible as a type variable for any operation you want to do, and it can be used in most places where a type is needed. It's not possible to go back from a Type
object to a type variable, and a Type
variable is very restricted in what it can do.
It does mean that you need to write more to create the MyType
object:
doSomethingWithSpecificTypesOnly<num>([MyType<int>(), MyType<double()]);
You can probably create a shorthand for that, like:
typedef T<X> = MyType<X>;
and then write [T<int>(), T<double>()]
instead. Slightly shorter.
Or
extension StaticType<T> on T {
MyType get staticType => MyType<T>;
}
and do something like:
[1.staticType, 1.1.staticType, "".staticType]
There are lots of options, depending on which API you want, but it won't be as short just [int, double]
, it's just more powerful than using Type
objects.
CodePudding user response:
This could be what you're looking for, however it will match the exact type:
class SomeClass {
}
void doSomethingWithSpecificTypesOnly<T>(List<Type> typesOfInterest, T obj) {
for (Type t in typesOfInterest) {
if (obj.runtimeType == t) {
print('ok');
print(obj.runtimeType);
}
}
}
void main() {
SomeClass obj = SomeClass();
doSomethingWithSpecificTypesOnly([int, SomeClass], obj);
doSomethingWithSpecificTypesOnly([int, double], obj);
return;
}