I have a generic function. I’m trying to return a value based on the type T,
however, my function never seems to match any types (see code below):
int _getCollection<T>() {
print(T); // the actual type
print(T is ClockData); // ClockData is a class I created
// always returns false when passing _getCollection<ClockData>()
if (T is ClockData) {
return 1;
} else if (T is UserData) {
return 2;
} else {
throw Exception();
}
}
>Solution :
is operator will check if left operand is an instance of right operand. T is a type parameter and not an instance of ClockData. You can use == operator to compare those:
int _getCollection<T>() {
if (T == ClockData) {
return 1;
} else if (T == UserData) {
return 2;
} else {
throw Exception();
}
}
Please not this checks for identity and will not support subtypes. If you need to support type inheritance (passing subclasses of ClockData as T) you can use a trick like this:
int _getCollection<T>() {
if (<T>[] is List<ClockData>) {
return 1;
} else if (<T>[] is List<UserData>) {
return 2;
} else {
throw Exception();
}
}